Merge pull request #432 from Sergio0694/dev/d2d-custom-transforms

Implement new D2D1 transform mapper infrastructure
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2022-11-29 14:48:04 -08:00
コミット f0b0edf516
45ファイル変更
+2604 -966

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

-15
ファイルの表示
@@ -1,15 +0,0 @@
namespace ComputeSharp.D2D1;
/// <summary>
/// An <see langword="interface"/> acting as a factory for <see cref="ID2D1TransformMapper{T}"/> instances.
/// </summary>
/// <typeparam name="T">The type of shader this factory creates transform mapper instances for.</typeparam>
public interface ID2D1TransformMapperFactory<T>
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// Creates a new <see cref="ID2D1TransformMapper{T}"/> instance for a given shader.
/// </summary>
/// <returns>A new <see cref="ID2D1TransformMapper{T}"/> instance for the input shader.</returns>
ID2D1TransformMapper<T> Create();
}
-78
ファイルの表示
@@ -1,78 +0,0 @@
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 ID2D1TransformMapper<T>
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// <para>
/// Allows a transform to state how it would map a a set of sample rectangles on its input to an output rectangle.
/// </para>
/// <para>
/// This is effectively the inverse mapping of <see cref="MapOutputToInputs"/>.
/// </para>
/// </summary>
/// <param name="shader">The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties).</param>
/// <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"/> and <see cref="MapInvalidOutput"/>, 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"/> and <see cref="MapOutputToInputs"/> 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(
in T shader,
ReadOnlySpan<Rectangle> inputs,
ReadOnlySpan<Rectangle> opaqueInputs,
out Rectangle output,
out Rectangle opaqueOutput);
/// <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>
/// 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"/>. Direct2D can call this method at any time
/// and in any sequence following a call to <see cref="MapInputsToOutput"/>.
/// </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);
}
+68
ファイルの表示
@@ -0,0 +1,68 @@
using System.Buffers;
using System.Runtime.CompilerServices;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
using ComputeSharp.D2D1.Shaders.Loaders;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.Interop;
/// <summary>
/// An object allowing <see cref="D2D1TransformMapper{T}.MapInputsToOutput"/> to interact with the shader data from within a transform.
/// </summary>
/// <typeparam name="T">The type of shader the transform will interact with.</typeparam>
public readonly unsafe ref struct D2D1DrawInfoUpdateContext<T>
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <see cref="ID2D1DrawInfoUpdateContext"/> instance associated with the current object.
/// </summary>
private readonly ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext;
/// <summary>
/// Creates a new <see cref="D2D1DrawInfoUpdateContext{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="d2D1DrawInfoUpdateContext">The <see cref="ID2D1DrawInfoUpdateContext"/> instance associated with the current object.</param>
internal D2D1DrawInfoUpdateContext(ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext)
{
this.d2D1DrawInfoUpdateContext = d2D1DrawInfoUpdateContext;
}
/// <summary>
/// Retrieves the <typeparamref name="T"/> instance currently being used in the associated effect.
/// </summary>
/// <returns>The <typeparamref name="T"/> instance currently being used in the associated effect.</returns>
public T GetConstantBuffer()
{
uint constantBufferSize;
this.d2D1DrawInfoUpdateContext->GetConstantBufferSize(&constantBufferSize).Assert();
byte[] buffer = ArrayPool<byte>.Shared.Rent((int)constantBufferSize);
fixed (byte* pBuffer = buffer)
{
this.d2D1DrawInfoUpdateContext->GetConstantBuffer(pBuffer, constantBufferSize).Assert();
}
Unsafe.SkipInit(out T shader);
shader.InitializeFromDispatchData(buffer);
ArrayPool<byte>.Shared.Return(buffer);
return shader;
}
/// <summary>
/// Updates the <typeparamref name="T"/> instance to be used in the associated effect.
/// </summary>
/// <param name="shader">The <typeparamref name="T"/> instance to be used in the associated effect.</param>
public void SetConstantBuffer(in T shader)
{
D2D1DrawInfoUpdateContextDispatchDataLoader dataLoader = new(this.d2D1DrawInfoUpdateContext);
Unsafe.AsRef(in shader).LoadDispatchData(ref dataLoader);
}
}
+107 -115
ファイルの表示
@@ -5,6 +5,7 @@ using ComputeSharp.D2D1.Helpers;
using ComputeSharp.D2D1.Interop.Effects;
using ComputeSharp.D2D1.Shaders.Interop.Buffers;
using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
using ComputeSharp.D2D1.Shaders.Loaders;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
@@ -35,53 +36,8 @@ public static unsafe class D2D1PixelShaderEffect
ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null.");
}
RegisterForD2D1Factory1<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="ID2D1TransformMapper{T}"/> 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>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="d2D1Factory1"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">Thrown if an effect is registered multiple times with different properties.</exception>
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</remarks>
public static void RegisterForD2D1Factory1<T, TMapper>(void* d2D1Factory1, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
where TMapper : class, ID2D1TransformMapper<T>, new()
{
if (d2D1Factory1 is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null.");
}
RegisterForD2D1Factory1(d2D1Factory1, D2D1TransformMapper.FactoryOf<T, TMapper>.Instance, 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="ID2D1TransformMapper{T}"/> 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>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="d2D1Factory1"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">Thrown if an effect is registered multiple times with different properties.</exception>
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</remarks>
public static void RegisterForD2D1Factory1<T>(void* d2D1Factory1, ID2D1TransformMapperFactory<T>? mapperFactory, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
{
if (d2D1Factory1 is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null.");
}
effectId = default;
PixelShaderEffect.For<T>.Initialize(mapperFactory);
ArrayPoolBufferWriter<char> writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize);
// Build the XML text
@@ -101,7 +57,7 @@ public static unsafe class D2D1PixelShaderEffect
""");
// Add the input nodes
for (int i = 0; i < PixelShaderEffect.For<T>.InputCount; i++)
for (int i = 0; i < PixelShaderEffect.For<T>.Instance.InputCount; i++)
{
writer.WriteRaw(" <Input name='Source");
writer.WriteAsUnicode(i);
@@ -165,6 +121,9 @@ public static unsafe class D2D1PixelShaderEffect
<Property name='ResourceTextureManager15' type='iunknown'>
<Property name='DisplayName' type='string' value='ResourceTextureManager15'/>
</Property>
<Property name='TransformMapper' type='iunknown'>
<Property name='DisplayName' type='string' value='TransformMapper'/>
</Property>
</Effect>
""");
@@ -172,26 +131,27 @@ public static unsafe class D2D1PixelShaderEffect
writer.WriteRaw('\0');
fixed (char* pXml = writer.WrittenSpan)
fixed (char* pBufferPropertyName = "ConstantBuffer")
fixed (char* pResourceTextureManager0PropertyName = "ResourceTextureManager0")
fixed (char* pResourceTextureManager1PropertyName = "ResourceTextureManager1")
fixed (char* pResourceTextureManager2PropertyName = "ResourceTextureManager2")
fixed (char* pResourceTextureManager3PropertyName = "ResourceTextureManager3")
fixed (char* pResourceTextureManager4PropertyName = "ResourceTextureManager4")
fixed (char* pResourceTextureManager5PropertyName = "ResourceTextureManager5")
fixed (char* pResourceTextureManager6PropertyName = "ResourceTextureManager6")
fixed (char* pResourceTextureManager7PropertyName = "ResourceTextureManager7")
fixed (char* pResourceTextureManager8PropertyName = "ResourceTextureManager8")
fixed (char* pResourceTextureManager9PropertyName = "ResourceTextureManager9")
fixed (char* pResourceTextureManager10PropertyName = "ResourceTextureManager10")
fixed (char* pResourceTextureManager11PropertyName = "ResourceTextureManager11")
fixed (char* pResourceTextureManager12PropertyName = "ResourceTextureManager12")
fixed (char* pResourceTextureManager13PropertyName = "ResourceTextureManager13")
fixed (char* pResourceTextureManager14PropertyName = "ResourceTextureManager14")
fixed (char* pResourceTextureManager15PropertyName = "ResourceTextureManager15")
fixed (char* pBufferPropertyName = nameof(D2D1PixelShaderEffectProperty.ConstantBuffer))
fixed (char* pResourceTextureManager0PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager0))
fixed (char* pResourceTextureManager1PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager1))
fixed (char* pResourceTextureManager2PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager2))
fixed (char* pResourceTextureManager3PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager3))
fixed (char* pResourceTextureManager4PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager4))
fixed (char* pResourceTextureManager5PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager5))
fixed (char* pResourceTextureManager6PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager6))
fixed (char* pResourceTextureManager7PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager7))
fixed (char* pResourceTextureManager8PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager8))
fixed (char* pResourceTextureManager9PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager9))
fixed (char* pResourceTextureManager10PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager10))
fixed (char* pResourceTextureManager11PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager11))
fixed (char* pResourceTextureManager12PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager12))
fixed (char* pResourceTextureManager13PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager13))
fixed (char* pResourceTextureManager14PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager14))
fixed (char* pResourceTextureManager15PropertyName = nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager15))
fixed (char* pTransformMapperPropertyName = nameof(D2D1PixelShaderEffectProperty.TransformMapper))
{
// Prepare the effect binding functions
D2D1_PROPERTY_BINDING* d2D1PropertyBinding = stackalloc D2D1_PROPERTY_BINDING[17];
D2D1_PROPERTY_BINDING* d2D1PropertyBinding = stackalloc D2D1_PROPERTY_BINDING[(int)D2D1PixelShaderEffectProperty.NumberOfProperties];
// Property names
d2D1PropertyBinding[0].propertyName = (ushort*)pBufferPropertyName;
@@ -211,6 +171,7 @@ public static unsafe class D2D1PixelShaderEffect
d2D1PropertyBinding[14].propertyName = (ushort*)pResourceTextureManager13PropertyName;
d2D1PropertyBinding[15].propertyName = (ushort*)pResourceTextureManager14PropertyName;
d2D1PropertyBinding[16].propertyName = (ushort*)pResourceTextureManager15PropertyName;
d2D1PropertyBinding[17].propertyName = (ushort*)pTransformMapperPropertyName;
// Property getters
d2D1PropertyBinding[0].getFunction = PixelShaderEffect.GetConstantBuffer;
@@ -230,6 +191,7 @@ public static unsafe class D2D1PixelShaderEffect
d2D1PropertyBinding[14].getFunction = PixelShaderEffect.GetResourceTextureManager13;
d2D1PropertyBinding[15].getFunction = PixelShaderEffect.GetResourceTextureManager14;
d2D1PropertyBinding[16].getFunction = PixelShaderEffect.GetResourceTextureManager15;
d2D1PropertyBinding[17].getFunction = PixelShaderEffect.GetTransformMapper;
// Property setters
d2D1PropertyBinding[0].setFunction = PixelShaderEffect.SetConstantBuffer;
@@ -249,59 +211,29 @@ public static unsafe class D2D1PixelShaderEffect
d2D1PropertyBinding[14].setFunction = PixelShaderEffect.SetResourceTextureManager13;
d2D1PropertyBinding[15].setFunction = PixelShaderEffect.SetResourceTextureManager14;
d2D1PropertyBinding[16].setFunction = PixelShaderEffect.SetResourceTextureManager15;
d2D1PropertyBinding[17].setFunction = PixelShaderEffect.SetTransformMapper;
fixed (Guid* pGuid = &PixelShaderEffect.For<T>.Id)
fixed (Guid* pGuid = &PixelShaderEffect.For<T>.Instance.Id)
{
// Register the effect
((ID2D1Factory1*)d2D1Factory1)->RegisterEffectFromString(
classId: pGuid,
propertyXml: (ushort*)pXml,
bindings: d2D1PropertyBinding,
bindingsCount: 17,
effectFactory: PixelShaderEffect.For<T>.Factory).Assert();
bindingsCount: D2D1PixelShaderEffectProperty.NumberOfProperties,
effectFactory: PixelShaderEffect.For<T>.Instance.Factory).Assert();
}
effectId = PixelShaderEffect.For<T>.Id;
effectId = PixelShaderEffect.For<T>.Instance.Id;
}
writer.Dispose();
}
/// <summary>
/// Gets a binary blob containing serialized information that can be used to register an effect, by using <c>ID2D1Factory1::RegisterEffectFromString</c>.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to register.</typeparam>
/// <param name="effectId">The <see cref="Guid"/> of the registered effect, which can be used to call <c>ID2D1DeviceContext::CreateEffect</c>.</param>
/// <returns>A blob containing serialized information that can be used to register an effect.</returns>
/// <exception cref="InvalidOperationException">Thrown if an effect is registered multiple times with different properties.</exception>
/// <remarks>For more info and for details on the binary format, see <see cref="GetRegistrationBlob{T}(ID2D1TransformMapperFactory{T}?, out Guid)"/>.</remarks>
public static ReadOnlyMemory<byte> GetRegistrationBlob<T>(out Guid effectId)
where T : unmanaged, ID2D1PixelShader
{
return GetRegistrationBlob<T>(null, out effectId);
}
/// <summary>
/// Gets a binary blob containing serialized information that can be used to register an effect, by using <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="ID2D1TransformMapper{T}"/> implementation to register.</typeparam>
/// <param name="effectId">The <see cref="Guid"/> of the registered effect, which can be used to call <c>ID2D1DeviceContext::CreateEffect</c>.</param>
/// <returns>A blob containing serialized information that can be used to register an effect.</returns>
/// <exception cref="InvalidOperationException">Thrown if an effect is registered multiple times with different properties.</exception>
/// <remarks>For more info and for details on the binary format, see <see cref="GetRegistrationBlob{T}(ID2D1TransformMapperFactory{T}?, out Guid)"/>.</remarks>
public static ReadOnlyMemory<byte> GetRegistrationBlob<T, TMapper>(out Guid effectId)
where T : unmanaged, ID2D1PixelShader
where TMapper : class, ID2D1TransformMapper<T>, new()
{
return GetRegistrationBlob(D2D1TransformMapper.FactoryOf<T, TMapper>.Instance, out effectId);
}
/// <summary>
/// Gets a binary blob containing serialized information that can be used to register an effect, by using <c>ID2D1Factory1::RegisterEffectFromString</c>.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to get the registration blob for.</typeparam>
/// <param name="mapperFactory">An optional factory of <see cref="ID2D1TransformMapper{T}"/> 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>
/// <returns>A blob containing serialized information that can be used to register an effect.</returns>
/// <exception cref="InvalidOperationException">Thrown if an effect is registered multiple times with different properties.</exception>
@@ -337,19 +269,17 @@ public static unsafe class D2D1PixelShaderEffect
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.
/// </para>
/// </remarks>
public static ReadOnlyMemory<byte> GetRegistrationBlob<T>(ID2D1TransformMapperFactory<T>? mapperFactory, out Guid effectId)
public static ReadOnlyMemory<byte> GetRegistrationBlob<T>(out Guid effectId)
where T : unmanaged, ID2D1PixelShader
{
PixelShaderEffect.For<T>.Initialize(mapperFactory);
ArrayPoolBufferWriter<byte> writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize);
// Blob id
writer.WriteRaw(D2D1EffectRegistrationData.V1.BlobId);
// Effect id and number of inputs
writer.WriteRaw(PixelShaderEffect.For<T>.Id);
writer.WriteRaw(PixelShaderEffect.For<T>.InputCount);
writer.WriteRaw(PixelShaderEffect.For<T>.Instance.Id);
writer.WriteRaw(PixelShaderEffect.For<T>.Instance.InputCount);
// Build the XML text
writer.WriteRaw("""
@@ -368,7 +298,7 @@ public static unsafe class D2D1PixelShaderEffect
"""u8);
// Add the input nodes
for (int i = 0; i < PixelShaderEffect.For<T>.InputCount; i++)
for (int i = 0; i < PixelShaderEffect.For<T>.Instance.InputCount; i++)
{
writer.WriteRaw(" <Input name='Source"u8);
writer.WriteAsUtf8(i);
@@ -432,6 +362,9 @@ public static unsafe class D2D1PixelShaderEffect
<Property name='ResourceTextureManager15' type='iunknown'>
<Property name='DisplayName' type='string' value='ResourceTextureManager15'/>
</Property>
<Property name='TransformMapper' type='iunknown'>
<Property name='DisplayName' type='string' value='TransformMapper'/>
</Property>
</Effect>
"""u8);
@@ -439,7 +372,7 @@ public static unsafe class D2D1PixelShaderEffect
writer.WriteRaw((byte)'\0');
// Bindings
writer.WriteRaw(17);
writer.WriteRaw(D2D1PixelShaderEffectProperty.NumberOfProperties);
writer.WriteRaw("ConstantBuffer"u8);
writer.WriteRaw((byte)'\0');
writer.WriteRaw((nint)PixelShaderEffect.GetConstantBuffer);
@@ -508,16 +441,20 @@ public static unsafe class D2D1PixelShaderEffect
writer.WriteRaw((byte)'\0');
writer.WriteRaw((nint)PixelShaderEffect.GetResourceTextureManager15);
writer.WriteRaw((nint)PixelShaderEffect.SetResourceTextureManager15);
writer.WriteRaw("TransformMapper"u8);
writer.WriteRaw((byte)'\0');
writer.WriteRaw((nint)PixelShaderEffect.GetTransformMapper);
writer.WriteRaw((nint)PixelShaderEffect.SetTransformMapper);
// Effect factory
writer.WriteRaw((nint)PixelShaderEffect.For<T>.Factory);
writer.WriteRaw((nint)PixelShaderEffect.For<T>.Instance.Factory);
byte[] registrationBlob = writer.WrittenSpan.ToArray();
writer.Dispose();
// Extract the effect id (the same that was encoded in the registration blob)
effectId = PixelShaderEffect.For<T>.Id;
effectId = PixelShaderEffect.For<T>.Instance.Id;
return registrationBlob;
}
@@ -548,14 +485,12 @@ public static unsafe class D2D1PixelShaderEffect
ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The pointer to the target ID2D1Effect result cannot be null.");
}
if (!PixelShaderEffect.For<T>.TryGetId(out Guid id))
fixed (Guid* pGuid = &PixelShaderEffect.For<T>.Instance.Id)
{
ThrowHelper.ThrowInvalidOperationException("The effect for the input shader type has not been initialized yet.");
((ID2D1DeviceContext*)d2D1DeviceContext)->CreateEffect(
effectId: pGuid,
effect: (ID2D1Effect**)d2D1Effect).Assert();
}
((ID2D1DeviceContext*)d2D1DeviceContext)->CreateEffect(
effectId: &id,
effect: (ID2D1Effect**)d2D1Effect).Assert();
}
/// <summary>
@@ -610,7 +545,7 @@ public static unsafe class D2D1PixelShaderEffect
/// Sets the resource texture manager from an input D2D1 effect, by calling <c>ID2D1Effect::SetValue</c>.
/// </summary>
/// <param name="d2D1Effect">A pointer to the <c>ID2D1Effect</c> instance to use.</param>
/// <param name="resourceTextureManager">The input <see cref="D2D1ResourceTextureManager"/> instance..</param>
/// <param name="resourceTextureManager">The input <see cref="D2D1ResourceTextureManager"/> instance.</param>
/// <param name="resourceTextureIndex">The index of the resource texture to assign the resource texture manager to.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="d2D1Effect"/> or <paramref name="resourceTextureManager"/> are <see langword="null"/>.</exception>
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1properties-setvalue(uint32_d2d1_property_type_constbyte_uint32)"/>.</remarks>
@@ -636,4 +571,61 @@ public static unsafe class D2D1PixelShaderEffect
data: (byte*)resourceTextureManager2.GetAddressOf(),
dataSize: (uint)sizeof(void*)).Assert();
}
/// <summary>
/// Sets the transform mapper for an input D2D1 effect, by calling <c>ID2D1Effect::SetValue</c>.
/// </summary>
/// <param name="d2D1Effect">A pointer to the <c>ID2D1Effect</c> instance to use.</param>
/// <param name="transformMapper">The input <c>ID2D1TransformMapper</c> object (see <see cref="D2D1TransformMapper{T}"/>).</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="d2D1Effect"/> or <paramref name="transformMapper"/> are <see langword="null"/>.</exception>
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1properties-setvalue(uint32_d2d1_property_type_constbyte_uint32)"/>.</remarks>
public static void SetTransformMapperForD2D1Effect(void* d2D1Effect, void* transformMapper)
{
if (d2D1Effect is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The input ID2D1Effect object cannot be null.");
}
if (transformMapper is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(transformMapper), "The input ID2D1TransformMapper object cannot be null.");
}
((ID2D1Effect*)d2D1Effect)->SetValue(
index: D2D1PixelShaderEffectProperty.TransformMapper,
type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_IUNKNOWN,
data: (byte*)&transformMapper,
dataSize: (uint)sizeof(void*)).Assert();
}
/// <summary>
/// Sets the transform mapper for an input D2D1 effect, by calling <c>ID2D1Effect::SetValue</c>.
/// </summary>
/// <param name="d2D1Effect">A pointer to the <c>ID2D1Effect</c> instance to use.</param>
/// <param name="transformMapper">The input <c>ID2D1TransformMapper</c> object.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="d2D1Effect"/> or <paramref name="transformMapper"/> are <see langword="null"/>.</exception>
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1properties-setvalue(uint32_d2d1_property_type_constbyte_uint32)"/>.</remarks>
public static void SetTransformMapperForD2D1Effect<T>(void* d2D1Effect, D2D1TransformMapper<T> transformMapper)
where T : unmanaged, ID2D1PixelShader
{
if (d2D1Effect is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The input ID2D1Effect object cannot be null.");
}
if (transformMapper is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(transformMapper), "The input D2D1TransformMapper<T> object cannot be null.");
}
using ComPtr<ID2D1TransformMapper> transformMapper2 = default;
transformMapper.GetD2D1TransformMapper(transformMapper2.GetAddressOf());
((ID2D1Effect*)d2D1Effect)->SetValue(
index: D2D1PixelShaderEffectProperty.TransformMapper,
type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_IUNKNOWN,
data: (byte*)transformMapper2.GetAddressOf(),
dataSize: (uint)sizeof(void*)).Assert();
}
}
+16
ファイルの表示
@@ -112,4 +112,20 @@ public static class D2D1PixelShaderEffectProperty
/// </summary>
/// <remarks>For more info, see <see cref="D2D1ResourceTextureManager"/>.</remarks>
public const uint ResourceTextureManager15 = 16;
/// <summary>
/// The index for the <c>ID2D1TransformMapper</c> property of a <see cref="D2D1PixelShaderEffect"/> object.
/// </summary>
/// <remarks>
/// <para>The value of this property is of type <c>D2D1_PROPERTY_TYPE_IUNKNOWN</c>.</para>
/// <para>This value can be passed when calling <c>ID2D1Effect::SetValue</c>.</para>
/// <para>For more info, see <see href="https://learn.microsoft.com/en-us/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1properties-setvalue(uint32_d2d1_property_type_constbyte_uint32)"/>.</para>
/// </remarks>
public const uint TransformMapper = 17;
/// <summary>
/// The total number of properties.
/// </summary>
/// <remarks>This should always be the value of the last property above, plus 1.</remarks>
internal const uint NumberOfProperties = 18;
}
+10 -14
ファイルの表示
@@ -1,6 +1,7 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
@@ -77,8 +78,8 @@ namespace ComputeSharp.D2D1.Interop;
/// interface ID2D1ResourceTextureManagerInternal : IUnknown
/// {
/// HRESULT Initialize(
/// [in] ID2D1EffectContext *effectContext,
/// [in, optional] const UINT32 *dimensions);
/// [in] const ID2D1EffectContext *effectContext,
/// [in, optional] const UINT32 *dimensions);
///
/// HRESULT GetResourceTexture([out] ID2D1ResourceTexture **resourceTexture);
/// };
@@ -105,7 +106,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface
/// <summary>
/// The <see cref="D2D1ResourceTextureManagerImpl"/> object wrapped by the current instance.
/// </summary>
private readonly D2D1ResourceTextureManagerImpl* d2D1ResourceManagerImpl;
private ComPtr<D2D1ResourceTextureManagerImpl> d2D1ResourceManagerImpl;
/// <summary>
/// Creates a new <see cref="D2D1ResourceTextureManager"/> instance with the specified parameters.
@@ -305,7 +306,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface
Marshal.ThrowExceptionForHR(E.E_INVALIDARG);
}
fixed (D2D1ResourceTextureManagerImpl** d2D1ResourceManagerImpl = &this.d2D1ResourceManagerImpl)
fixed (D2D1ResourceTextureManagerImpl** d2D1ResourceManagerImpl = this.d2D1ResourceManagerImpl)
{
D2D1ResourceTextureManagerImpl.Factory(d2D1ResourceManagerImpl, requiresMultithread: true);
}
@@ -324,7 +325,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface
d2D1ResourceTextureProperties.extendModes = (D2D1_EXTEND_MODE*)pExtendModes;
int hresult = D2D1ResourceTextureManagerImpl.Initialize(
@this: this.d2D1ResourceManagerImpl,
@this: this.d2D1ResourceManagerImpl.Get(),
resourceId: resourceId,
resourceTextureProperties: &d2D1ResourceTextureProperties,
data: pData,
@@ -340,10 +341,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface
/// </summary>
~D2D1ResourceTextureManager()
{
if (this.d2D1ResourceManagerImpl is not null)
{
_ = this.d2D1ResourceManagerImpl->Release();
}
this.d2D1ResourceManagerImpl.Dispose();
}
/// <summary>
@@ -376,7 +374,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface
}
int hresult = D2D1ResourceTextureManagerImpl.Update(
@this: this.d2D1ResourceManagerImpl,
@this: this.d2D1ResourceManagerImpl.Get(),
minimumExtents: pMinimumExtents,
maximimumExtents: pMaximumExtents,
strides: pStrides,
@@ -397,9 +395,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void GetD2D1ResourceTextureManager(ID2D1ResourceTextureManager** resourceTextureManager)
{
_ = this.d2D1ResourceManagerImpl->AddRef();
*resourceTextureManager = (ID2D1ResourceTextureManager*)this.d2D1ResourceManagerImpl;
this.d2D1ResourceManagerImpl.CopyTo(resourceTextureManager).Assert();
GC.KeepAlive(this);
}
@@ -410,7 +406,7 @@ public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface
fixed (Guid* pIid = &iid)
fixed (IntPtr* pPpv = &ppv)
{
int hresult = this.d2D1ResourceManagerImpl->QueryInterface(pIid, (void**)pPpv);
int hresult = this.d2D1ResourceManagerImpl.CopyTo(pIid, (void**)pPpv);
GC.KeepAlive(this);
+24 -24
ファイルの表示
@@ -12,81 +12,81 @@ public static class D2D1TransformMapperFactory<T>
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// Creates an <see cref="ID2D1TransformMapperFactory{T}"/> instance for an inflate transform.
/// Creates an <see cref="D2D1TransformMapper{T}"/> instance for an inflate transform.
/// </summary>
/// <param name="amount">The fixed inflate amount to use (applies to all edges of the input area).</param>
/// <returns>The resulting <see cref="ID2D1TransformMapperFactory{T}"/> instance for an inflate transform.</returns>
public static ID2D1TransformMapperFactory<T> Inflate(int amount)
/// <returns>The resulting <see cref="D2D1TransformMapper{T}"/> instance for an inflate transform.</returns>
public static D2D1TransformMapper<T> Inflate(int amount)
{
return new D2D1InflateTransformMapperFactory<T> { ParametersAccessor = new D2D1InflateTransformMapperFactory<T>.ConstantAmount { Amount = amount } };
return new D2D1InflateTransformMapper<T>.ConstantAmount { Amount = amount };
}
/// <summary>
/// Creates an <see cref="ID2D1TransformMapperFactory{T}"/> instance for an inflate transform.
/// Creates an <see cref="D2D1TransformMapper{T}"/> instance for an inflate transform.
/// </summary>
/// <param name="left">The fixed left inflate amount to use.</param>
/// <param name="top">The fixed top inflate amount to use.</param>
/// <param name="right">The fixed right inflate amount to use.</param>
/// <param name="bottom">The fixed bottom inflate amount to use.</param>
/// <returns>The resulting <see cref="ID2D1TransformMapperFactory{T}"/> instance for an inflate transform.</returns>
public static ID2D1TransformMapperFactory<T> Inflate(int left, int top, int right, int bottom)
/// <returns>The resulting <see cref="D2D1TransformMapper{T}"/> instance for an inflate transform.</returns>
public static D2D1TransformMapper<T> Inflate(int left, int top, int right, int bottom)
{
return new D2D1InflateTransformMapperFactory<T> { ParametersAccessor = new D2D1InflateTransformMapperFactory<T>.ConstantLeftTopRightBottomAmount { Left = left, Top = top, Right = right, Bottom = bottom } };
return new D2D1InflateTransformMapper<T>.ConstantLeftTopRightBottomAmount { Left = left, Top = top, Right = right, Bottom = bottom };
}
/// <summary>
/// Creates an <see cref="ID2D1TransformMapperFactory{T}"/> instance for an inflate transform.
/// Creates an <see cref="D2D1TransformMapper{T}"/> instance for an inflate transform.
/// </summary>
/// <param name="accessor">The input <see cref="Accessor{TResult}"/> instance to retrieve the inflate amount to use (applies to all edges of the input area).</param>
/// <returns>The resulting <see cref="ID2D1TransformMapperFactory{T}"/> instance for an inflate transform.</returns>
public static ID2D1TransformMapperFactory<T> Inflate(Accessor<int> accessor)
/// <returns>The resulting <see cref="D2D1TransformMapper{T}"/> instance for an inflate transform.</returns>
public static D2D1TransformMapper<T> Inflate(Accessor<int> accessor)
{
if (accessor is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(accessor), "The input D2D1TransformMapperFactory<T>.Accessor<int> object cannot be null.");
}
return new D2D1InflateTransformMapperFactory<T> { ParametersAccessor = new D2D1InflateTransformMapperFactory<T>.DynamicAmount { Accessor = accessor } };
return new D2D1InflateTransformMapper<T>.DynamicAmount { Accessor = accessor };
}
/// <summary>
/// Creates an <see cref="ID2D1TransformMapperFactory{T}"/> instance for an inflate transform.
/// Creates an <see cref="D2D1TransformMapper{T}"/> instance for an inflate transform.
/// </summary>
/// <param name="accessor">The input <see cref="Accessor{TResult}"/> instance to retrieve the inflate amount to use.</param>
/// <returns>The resulting <see cref="ID2D1TransformMapperFactory{T}"/> instance for an inflate transform.</returns>
public static ID2D1TransformMapperFactory<T> Inflate(Accessor<(int Left, int Top, int Right, int Bottom)> accessor)
/// <returns>The resulting <see cref="D2D1TransformMapper{T}"/> instance for an inflate transform.</returns>
public static D2D1TransformMapper<T> Inflate(Accessor<(int Left, int Top, int Right, int Bottom)> accessor)
{
if (accessor is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(accessor), "The input D2D1TransformMapperFactory<T>.Accessor<(int Left, int Top, int Right, int Bottom)> object cannot be null.");
}
return new D2D1InflateTransformMapperFactory<T> { ParametersAccessor = new D2D1InflateTransformMapperFactory<T>.DynamicLeftTopRightBottomAmount { Accessor = accessor } };
return new D2D1InflateTransformMapper<T>.DynamicLeftTopRightBottomAmount { Accessor = accessor };
}
/// <summary>
/// Creates an <see cref="ID2D1TransformMapperFactory{T}"/> instance for an affine transform.
/// Creates an <see cref="D2D1TransformMapper{T}"/> instance for an affine transform.
/// </summary>
/// <param name="matrix">The fixed transformation matrix to use.</param>
/// <returns>The resulting <see cref="ID2D1TransformMapperFactory{T}"/> instance for an affine transform.</returns>
public static ID2D1TransformMapperFactory<T> Transform(Matrix3x2 matrix)
/// <returns>The resulting <see cref="D2D1TransformMapper{T}"/> instance for an affine transform.</returns>
public static D2D1TransformMapper<T> Transform(Matrix3x2 matrix)
{
return new D2D1AffineTransformMapperFactory.For<T> { ParametersAccessor = new D2D1AffineTransformMapperFactory.For<T>.ConstantMatrix { Amount = matrix } };
return new D2D1AffineTransformMapper<T>.ConstantMatrix { Amount = matrix };
}
/// <summary>
/// Creates an <see cref="ID2D1TransformMapperFactory{T}"/> instance for an affine transform.
/// Creates an <see cref="D2D1TransformMapper{T}"/> instance for an affine transform.
/// </summary>
/// <param name="accessor">The input <see cref="Accessor{TResult}"/> instance to retrieve the transformation matrix to use.</param>
/// <returns>The resulting <see cref="ID2D1TransformMapperFactory{T}"/> instance for an affine transform.</returns>
public static ID2D1TransformMapperFactory<T> Transform(Accessor<Matrix3x2> accessor)
/// <returns>The resulting <see cref="D2D1TransformMapper{T}"/> instance for an affine transform.</returns>
public static D2D1TransformMapper<T> Transform(Accessor<Matrix3x2> accessor)
{
if (accessor is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(accessor), "The input D2D1TransformMapperFactory<T>.Accessor<Matrix3x2> object cannot be null.");
}
return new D2D1AffineTransformMapperFactory.For<T> { ParametersAccessor = new D2D1AffineTransformMapperFactory.For<T>.DynamicMatrix { Accessor = accessor } };
return new D2D1AffineTransformMapper<T>.DynamicMatrix { Accessor = accessor };
}
/// <summary>
+277
ファイルの表示
@@ -0,0 +1,277 @@
using System;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Interop.Effects;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
using TerraFX.Interop.Windows;
#pragma warning disable CA1033
namespace ComputeSharp.D2D1.Interop;
/// <summary>
/// Provides an <c>ID2D1TransformMapper</c> implementation, which can be used to customize the draw transform logic in
/// an effect created with <see cref="D2D1PixelShaderEffect"/> and also shared across multiple instances of a given effect.
/// </summary>
/// <typeparam name="T">The type of shader the transform will interact with.</typeparam>
/// <remarks>
/// <para>
/// The built-in <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nn-d2d1effectauthor-id2d1effectimpl"><c>ID2D1EffectImpl</c></see>
/// implementation provided by <see cref="D2D1PixelShaderEffect"/> (which makes it possible to register and create
/// <see href="https://docs.microsoft.com/en-us/windows/win32/api/d2d1_1/nn-d2d1_1-id2d1effect"><c>ID2D1Effect</c></see>
/// instances that can be used to run D2D1 pixel shaders) uses draw transform objects to allow customizing the transform logic externally.
/// </para>
/// <para>
/// These managers are COM objects implementing the following interface:
/// <code language="cpp">
/// [uuid(02E6D48D-B892-4FBC-AA54-119203BAB802)]
/// interface ID2D1TransformMapper : IUnknown
/// {
/// HRESULT MapInputRectsToOutputRect(
/// [in] const ID2D1DrawInfoUpdateContext* updateContext,
/// [in] const RECT* inputRects,
/// [in] const RECT* inputOpaqueSubRects,
/// UINT32 inputRectCount,
/// [out] RECT* outputRect,
/// [out] RECT* outputOpaqueSubRect);
///
/// HRESULT MapOutputRectToInputRects(
/// [in] const RECT* outputRect,
/// [out] RECT* inputRects,
/// UINT32 inputRectsCount);
///
/// HRESULT MapInvalidRect(
/// UINT32 inputIndex,
/// RECT invalidInputRect,
/// [out] RECT* invalidOutputRect);
/// };
/// </code>
/// </para>
/// <para>
/// These can be used to implement custom draw transform logic, assign it to an effect and also share these transforms over multiple effects.
/// </para>
/// <para>
/// For details of how these work, <c>MapInputRectsToOutputRect</c> maps to
/// <see href="https://learn.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapinputrectstooutputrect"><c>ID2D1Transform::MapInputRectsToOutputRect</c></see>,
/// <c>MapOutputRectToInputRects</c> maps to <see href="https://learn.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapoutputrecttoinputrects"><c>ID2D1Transform::MapOutputRectToInputRects</c></see>.
/// and <c>MapInvalidRect</c> maps to <see href="https://learn.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapinvalidrect"><c>ID2D1Transform::MapInvalidRect</c></see>.
/// </para>
/// <para>
/// The main difference between these APIs and the ones in <c>ID2D1Transform</c> is the fact that this interface is standalone (ie. it doesn't inherit from <c>ID2D1TransformNode</c>),
/// and that it allows transform mappers to also read and update additional data tied to an effect instance (such as the shader constant buffer). This is done through the
/// <c>ID2D1DrawInfoUpdateContext</c> interface, that is passed to <c>MapInputRectsToOutputRect</c>. This interface is defined as follows:
/// <code>
/// [uuid(430C5B40-AE16-485F-90E6-4FA4915144B6)]
/// interface ID2D1DrawInfoUpdateContext : IUnknown
/// {
/// HRESULT GetConstantBufferSize([out] UINT32 *size);
///
/// HRESULT GetConstantBuffer(
/// [out] BYTE *buffer,
/// UINT32 bufferCount);
///
/// HRESULT SetConstantBuffer(
/// [in] const BYTE *buffer,
/// UINT32 bufferCount);
/// }
/// </code>
/// </para>
/// <para>
/// That is, <c>ID2D1DrawInfoUpdateContext</c> allows a custom transform (an <c>ID2D1TransformMapper</c> instance) to interact with the underlying <c>ID2D1DrawInfo</c> object
/// that is owned by the effect being used, in a safe way. For instance, it allows a transform to read and update the constant buffer, which can be used to allow a transform to
/// pass the exact dispatch area size to an input shader, without the consumer having to manually query that information beforehand (which might not be available either).
/// </para>
/// <para>
/// This interface is implemented by ComputeSharp.D2D1, and it can be used through the APIs in <see cref="D2D1TransformMapper{T}"/>, in several ways.
/// That is, consumers can either implement a type inheriting from <see cref="D2D1TransformMapper{T}"/> to implement their own fully customized transform
/// mapping logic, or they can use the helper methods exposed by <see cref="D2D1TransformMapperFactory{T}"/> to easily retrieve ready to use transforms.
/// </para>
/// <para>
/// A CCW (COM callable wrapper, see <see href="https://learn.microsoft.com/dotnet/standard/native-interop/com-callable-wrapper"/>) is also available for all
/// of these APIs, implemented via the same <see cref="D2D1TransformMapper{T}"/> type. That is, a given instance can expose its underlying CCW through the
/// <see cref="ICustomQueryInterface"/> interface, and this can then be passed to an existing D2D1 effect instance.
/// </para>
/// </remarks>
public abstract unsafe class D2D1TransformMapper<T> : ICustomQueryInterface, ID2D1TransformMapperInterop
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <see cref="D2D1TransformMapperImpl"/> object wrapped by the current instance.
/// </summary>
private ComPtr<D2D1TransformMapperImpl> d2D1TransformMapperImpl;
/// <summary>
/// Creates a new <see cref="D2D1TransformMapper{T}"/> instance.
/// </summary>
public D2D1TransformMapper()
{
fixed (D2D1TransformMapperImpl** d2D1TransformMapperImpl = this.d2D1TransformMapperImpl)
{
D2D1TransformMapperImpl.Factory(this, d2D1TransformMapperImpl);
}
}
/// <summary>
/// Releases the underlying <c>ID2D1TransformMapper</c> object.
/// </summary>
~D2D1TransformMapper()
{
this.d2D1TransformMapperImpl.Dispose();
}
/// <summary>
/// <para>
/// Allows a transform to state how it would map a a set of sample rectangles on its input to an output rectangle.
/// </para>
/// <para>
/// This is effectively the inverse mapping of <see cref="MapOutputToInputs"/>.
/// </para>
/// </summary>
/// <param name="drawInfoUpdateContext">The input <see cref="D2D1DrawInfoUpdateContext{T}"/> value, which can be used to access and modify shader data.</param>
/// <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"/> and <see cref="MapInvalidOutput"/>, 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"/> and <see cref="MapOutputToInputs"/> methods.
/// </para>
/// <para>
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapinputrectstooutputrect"/>.
/// </para>
/// </remarks>
public abstract void MapInputsToOutput(
D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext,
ReadOnlySpan<Rectangle> inputs,
ReadOnlySpan<Rectangle> opaqueInputs,
out Rectangle output,
out Rectangle opaqueOutput);
/// <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>
public abstract void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs);
/// <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"/>. Direct2D can call this method at any time
/// and in any sequence following a call to <see cref="MapInputsToOutput"/>.
/// </para>
/// <para>
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapinvalidrect"/>.
/// </para>
/// </remarks>
public abstract void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput);
/// <summary>
/// Gets the underlying <see cref="ID2D1TransformMapper"/> object.
/// </summary>
/// <param name="transformMapper">The underlying <see cref="ID2D1TransformMapper"/> object.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void GetD2D1TransformMapper(ID2D1TransformMapper** transformMapper)
{
bool lockTaken = false;
this.d2D1TransformMapperImpl.Get()->SpinLock.Enter(ref lockTaken);
// Whenever the CCW is requested from this object, we also make sure that the current instance is tracked
// in the GC handle stored in the CCW. This could've been reset in case there were no other references to
// the CCW (see comments in D2D1TransformMapperImpl about this), so here we're assigning a reference to the
// current object again to ensure the returned CCW object will keep the instance alive if needed.
try
{
this.d2D1TransformMapperImpl.Get()->EnsureTargetIsTracked(this);
this.d2D1TransformMapperImpl.Get()->CopyToWithNoLock(transformMapper);
}
finally
{
this.d2D1TransformMapperImpl.Get()->SpinLock.Exit();
GC.KeepAlive(this);
}
}
/// <inheritdoc/>
CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv)
{
fixed (Guid* pIid = &iid)
fixed (IntPtr* pPpv = &ppv)
{
int hresult;
bool lockTaken = false;
this.d2D1TransformMapperImpl.Get()->SpinLock.Enter(ref lockTaken);
try
{
this.d2D1TransformMapperImpl.Get()->EnsureTargetIsTracked(this);
hresult = this.d2D1TransformMapperImpl.Get()->QueryInterfaceWithNoLock(pIid, (void**)pPpv);
}
finally
{
this.d2D1TransformMapperImpl.Get()->SpinLock.Exit();
GC.KeepAlive(this);
}
return hresult switch
{
S.S_OK => CustomQueryInterfaceResult.Handled,
_ => CustomQueryInterfaceResult.Failed
};
}
}
/// <inheritdoc/>
void ID2D1TransformMapperInterop.MapInputsToOutput(
ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext,
ReadOnlySpan<Rectangle> inputs,
ReadOnlySpan<Rectangle> opaqueInputs,
out Rectangle output,
out Rectangle opaqueOutput)
{
MapInputsToOutput(
new D2D1DrawInfoUpdateContext<T>(d2D1DrawInfoUpdateContext),
inputs,
opaqueInputs,
out output,
out opaqueOutput);
}
/// <inheritdoc/>
void ID2D1TransformMapperInterop.MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs)
{
MapOutputToInputs(in output, inputs);
}
/// <inheritdoc/>
void ID2D1TransformMapperInterop.MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput)
{
MapInvalidOutput(inputIndex, in invalidInput, out invalidOutput);
}
}
-133
ファイルの表示
@@ -1,133 +0,0 @@
using System;
using System.Drawing;
using System.Runtime.CompilerServices;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.Interop.Effects;
/// <summary>
/// A base type to support non-generic <see cref="ID2D1TransformMapper{T}"/> uses.
/// </summary>
internal abstract class D2D1TransformMapper
{
/// <inheritdoc cref="ID2D1TransformMapper{T}.MapInputsToOutput"/>
/// <param name="buffer">The buffer with the serialized shader dispatch data, if any.</param>
/// <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>
public abstract void MapInputsToOutput(
ReadOnlySpan<byte> buffer,
ReadOnlySpan<Rectangle> inputs,
ReadOnlySpan<Rectangle> opaqueInputs,
out Rectangle output,
out Rectangle opaqueOutput);
/// <inheritdoc cref="ID2D1TransformMapper{T}.MapOutputToInputs"/>
/// <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>
public abstract void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs);
/// <inheritdoc cref="ID2D1TransformMapper{T}.MapInvalidOutput"/>
/// <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>
public abstract void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput);
/// <summary>
/// A generic <see cref="D2D1TransformMapper"/> implementation for a specific shader type.
/// </summary>
/// <typeparam name="T">The target shader type.</typeparam>
public sealed class For<T> : D2D1TransformMapper
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <see cref="ID2D1TransformMapper{T}"/> instance to use.
/// </summary>
private readonly ID2D1TransformMapper<T> transformMapper;
/// <summary>
/// Creates a new <see cref="For{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="transformMapper">The <see cref="ID2D1TransformMapper{T}"/> instance to use.</param>
private For(ID2D1TransformMapper<T> transformMapper)
{
this.transformMapper = transformMapper;
}
/// <summary>
/// Creates a new <see cref="For{T}"/> instance for a given transform mapper, if there is one.
/// </summary>
/// <param name="transformMapper">The <see cref="ID2D1TransformMapper{T}"/> instance to usse, if there is one.</param>
/// <returns>A new <see cref="For{T}"/> instance wrapping <paramref name="transformMapper"/>, or <see langword="null"/>.</returns>
public static D2D1TransformMapper? Get(ID2D1TransformMapper<T>? transformMapper)
{
if (transformMapper is null)
{
return null;
}
// If one of the built-in transform mapper factories from D2D1TransformMapperFactory<T> was used,
// the returned ID2D1TransformMapper<T> instance will already inherit from D2D1TransformMapper.
// If that's the case, that object can be returned directly, saving one allocation and avoiding
// an extra interface stub dispatch call every time one of the transform mapping APIs is called.
if (transformMapper is D2D1TransformMapper d2D1TransformMapper)
{
return d2D1TransformMapper;
}
return new For<T>(transformMapper);
}
/// <inheritdoc/>
public override void MapInputsToOutput(ReadOnlySpan<byte> buffer, ReadOnlySpan<Rectangle> inputs, ReadOnlySpan<Rectangle> opaqueInputs, out Rectangle output, out Rectangle opaqueOutput)
{
Unsafe.SkipInit(out T shader);
shader.InitializeFromDispatchData(buffer);
this.transformMapper.MapInputsToOutput(in shader, inputs, opaqueInputs, out output, out opaqueOutput);
}
/// <inheritdoc/>
public override void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs)
{
this.transformMapper.MapOutputToInputs(in output, inputs);
}
/// <inheritdoc/>
public override void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput)
{
this.transformMapper.MapInvalidOutput(inputIndex, invalidInput, out invalidOutput);
}
}
/// <summary>
/// A generic <see cref="ID2D1TransformMapperFactory{T}"/> implementation for a mapper with a parameterless constructor.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to register.</typeparam>
/// <typeparam name="TMapper">The type of <see cref="ID2D1TransformMapper{T}"/> implementation to register.</typeparam>
public sealed class FactoryOf<T, TMapper> : ID2D1TransformMapperFactory<T>
where T : unmanaged, ID2D1PixelShader
where TMapper : class, ID2D1TransformMapper<T>, new()
{
/// <summary>
/// Creates a new <see cref="FactoryOf{T, TMapper}"/> instance.
/// </summary>
private FactoryOf()
{
}
/// <summary>
/// Gets the shared <see cref="FactoryOf{T, TMapper}"/> instance for a given transform mapper.
/// </summary>
public static FactoryOf<T, TMapper> Instance { get; } = new();
/// <inheritdoc/>
public ID2D1TransformMapper<T> Create()
{
return new TMapper();
}
}
}
+30
ファイルの表示
@@ -0,0 +1,30 @@
using System;
using System.Drawing;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
namespace ComputeSharp.D2D1.Interop.Effects;
/// <summary>
/// A base type to support non-generic <see cref="D2D1TransformMapper{T}"/> uses.
/// </summary>
internal unsafe interface ID2D1TransformMapperInterop
{
/// <inheritdoc cref="D2D1TransformMapper{T}.MapInputsToOutput"/>
/// <param name="d2D1DrawInfoUpdateContext">The <see cref="ID2D1DrawInfoUpdateContext"/> instance associated with the current effect.</param>
/// <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>
void MapInputsToOutput(
ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext,
ReadOnlySpan<Rectangle> inputs,
ReadOnlySpan<Rectangle> opaqueInputs,
out Rectangle output,
out Rectangle opaqueOutput);
/// <inheritdoc cref="D2D1TransformMapper{T}.MapOutputToInputs"/>
void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs);
/// <inheritdoc cref="D2D1TransformMapper{T}.MapInvalidOutput"/>
void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput);
}
+154 -164
ファイルの表示
@@ -1,7 +1,6 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Helpers;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if NET6_0_OR_GREATER
@@ -10,8 +9,6 @@ using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers;
using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
#endif
#pragma warning disable CA2002
namespace ComputeSharp.D2D1.Interop.Effects;
/// <summary>
@@ -19,22 +16,25 @@ namespace ComputeSharp.D2D1.Interop.Effects;
/// </summary>
internal unsafe partial struct PixelShaderEffect
{
/// <summary>
/// A wrapper for an effect factory.
/// </summary>
/// <param name="effectImpl">The resulting effect factory.</param>
/// <returns>The <c>HRESULT</c> for the operation.</returns>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int FactoryDelegate(IUnknown** effectImpl);
/// <summary>
/// A generic pixel shader implementation.
/// </summary>
/// <typeparam name="T">The type of shader.</typeparam>
public static class For<T>
public sealed class For<T>
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <see cref="FactoryDelegate"/> wrapper for the shader factory.
/// </summary>
private static readonly FactoryDelegate EffectFactory = CreateEffect;
/// <summary>
/// Indicates whether or not initialization has completed.
/// </summary>
private static bool isInitialized;
private readonly FactoryDelegate effectFactory;
/// <summary>
/// The <see cref="Guid"/> for the shader.
@@ -44,229 +44,168 @@ internal unsafe partial struct PixelShaderEffect
/// being used to pass its address to a native API, but the attribute is incompatible with collectible assemblies.
/// Because of that, it can't be used, as this project is explicitly meant to support plugin-like scenarios.
/// </remarks>
private static Guid shaderId;
private readonly Guid shaderId;
/// <summary>
/// The size of the constant buffer for the shader.
/// </summary>
private static int constantBufferSize;
private readonly int constantBufferSize;
/// <summary>
/// The number of inputs for the shader.
/// </summary>
private static int inputCount;
private readonly int inputCount;
/// <summary>
/// The buffer with the types of inputs for the shader.
/// </summary>
private static D2D1PixelShaderInputType* inputTypes;
private readonly D2D1PixelShaderInputType* inputTypes;
/// <summary>
/// The number of available input descriptions.
/// </summary>
private static int inputDescriptionCount;
private readonly int inputDescriptionCount;
/// <summary>
/// The buffer with the available input descriptions for the shader.
/// </summary>
private static D2D1InputDescription* inputDescriptions;
private readonly D2D1InputDescription* inputDescriptions;
/// <summary>
/// The pixel options for the shader.
/// </summary>
private static D2D1PixelOptions pixelOptions;
private readonly D2D1PixelOptions pixelOptions;
/// <summary>
/// The shader bytecode.
/// </summary>
private static byte* bytecode;
private readonly byte* bytecode;
/// <summary>
/// The size of <see cref="bytecode"/>.
/// </summary>
private static int bytecodeSize;
private readonly int bytecodeSize;
/// <summary>
/// The buffer precision for the resulting output buffer.
/// </summary>
private static D2D1BufferPrecision bufferPrecision;
private readonly D2D1BufferPrecision bufferPrecision;
/// <summary>
/// The channel depth for the resulting output buffer.
/// </summary>
private static D2D1ChannelDepth channelDepth;
private readonly D2D1ChannelDepth channelDepth;
/// <summary>
/// The number of available resource texture descriptions.
/// </summary>
private static int resourceTextureDescriptionCount;
private readonly int resourceTextureDescriptionCount;
/// <summary>
/// The buffer with the available resource texture descriptions for the shader.
/// </summary>
private static D2D1ResourceTextureDescription* resourceTextureDescriptions;
private readonly D2D1ResourceTextureDescription* resourceTextureDescriptions;
/// <summary>
/// The factory of <see cref="ID2D1TransformMapper{T}"/> instances to use for each created effect.
/// Creates a new <see cref="For{T}"/> instance with the specified parameters.
/// </summary>
private static ID2D1TransformMapperFactory<T>? d2D1DrawTransformMapperFactory;
/// <summary>
/// Initializes the <see cref="For{T}"/> shared state.
/// </summary>
/// <param name="d2D1DrawTransformMapperFactory">The factory of <see cref="ID2D1TransformMapper{T}"/> 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(ID2D1TransformMapperFactory<T>? d2D1DrawTransformMapperFactory)
/// <param name="effectFactory">The <see cref="FactoryDelegate"/> wrapper for the shader factory.</param>
/// <param name="shaderId">The <see cref="Guid"/> for the shader.</param>
/// <param name="constantBufferSize">The size of the constant buffer for the shader.</param>
/// <param name="inputCount">The number of inputs for the shader.</param>
/// <param name="inputTypes">The buffer with the types of inputs for the shader.</param>
/// <param name="inputDescriptionCount">The number of available input descriptions.</param>
/// <param name="inputDescriptions">The buffer with the available input descriptions for the shader.</param>
/// <param name="pixelOptions">The pixel options for the shader.</param>
/// <param name="bytecode">The shader bytecode.</param>
/// <param name="bytecodeSize">The size of <paramref name="bytecode"/>.</param>
/// <param name="bufferPrecision">The buffer precision for the resulting output buffer.</param>
/// <param name="channelDepth">The channel depth for the resulting output buffer.</param>
/// <param name="resourceTextureDescriptionCount">The number of available resource texture descriptions.</param>
/// <param name="resourceTextureDescriptions">The buffer with the available resource texture descriptions for the shader.</param>
private For(
FactoryDelegate effectFactory,
Guid shaderId,
int constantBufferSize,
int inputCount,
D2D1PixelShaderInputType* inputTypes,
int inputDescriptionCount,
D2D1InputDescription* inputDescriptions,
D2D1PixelOptions pixelOptions,
byte* bytecode,
int bytecodeSize,
D2D1BufferPrecision bufferPrecision,
D2D1ChannelDepth channelDepth,
int resourceTextureDescriptionCount,
D2D1ResourceTextureDescription* resourceTextureDescriptions)
{
// 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 (For<T>.d2D1DrawTransformMapperFactory != d2D1DrawTransformMapperFactory)
{
ThrowHelper.ThrowInvalidOperationException(
"Cannot initialize an ID2D1Effect factory for the same shader type with two different transform mapper factories. " +
"Make sure to only ever register a pixel shader effect with either no transform, or the same transform mapper factory instance.");
}
}
else
{
// Load all shader properties
Guid shaderId = typeof(T).GUID;
int constantBufferSize = D2D1PixelShader.GetConstantBufferSize<T>();
D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision<T>();
D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth<T>();
D2D1PixelOptions pixelOptions = D2D1PixelShader.GetPixelOptions<T>();
// Prepare the inputs info
int inputCount = D2D1PixelShader.GetInputCount<T>();
D2D1PixelShaderInputType* inputTypes = (D2D1PixelShaderInputType*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), sizeof(D2D1PixelShaderInputType) * inputCount);
for (int i = 0; i < inputCount; i++)
{
inputTypes[i] = D2D1PixelShader.GetInputType<T>(i);
}
// Prepare the input descriptions
ReadOnlyMemory<D2D1InputDescription> inputDescriptionsInfo = D2D1PixelShader.GetInputDescriptions<T>();
int inputDescriptionCount = inputDescriptionsInfo.Length;
D2D1InputDescription* inputDescriptions = (D2D1InputDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), sizeof(D2D1InputDescription) * inputDescriptionCount);
inputDescriptionsInfo.Span.CopyTo(new Span<D2D1InputDescription>(inputDescriptions, inputDescriptionCount));
// Prepare the resource texture descriptions
ReadOnlyMemory<D2D1ResourceTextureDescription> resourceTextureDescriptionsInfo = D2D1PixelShader.GetResourceTextureDescriptions<T>();
int resourceTextureDescriptionCount = resourceTextureDescriptionsInfo.Length;
D2D1ResourceTextureDescription* resourceTextureDescriptions = (D2D1ResourceTextureDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), sizeof(D2D1ResourceTextureDescription) * resourceTextureDescriptionCount);
resourceTextureDescriptionsInfo.Span.CopyTo(new Span<D2D1ResourceTextureDescription>(resourceTextureDescriptions, resourceTextureDescriptionCount));
// Copy the bytecode to the target buffer
ReadOnlyMemory<byte> bytecodeInfo = D2D1PixelShader.LoadBytecode<T>();
int bytecodeSize = bytecodeInfo.Length;
byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), bytecodeSize);
bytecodeInfo.Span.CopyTo(new Span<byte>(bytecode, bytecodeSize));
// Set the shared state and mark the type as initialized
For<T>.shaderId = shaderId;
For<T>.constantBufferSize = constantBufferSize;
For<T>.inputCount = inputCount;
For<T>.inputTypes = inputTypes;
For<T>.inputDescriptionCount = inputDescriptionCount;
For<T>.inputDescriptions = inputDescriptions;
For<T>.pixelOptions = pixelOptions;
For<T>.bytecode = bytecode;
For<T>.bytecodeSize = bytecodeSize;
For<T>.bufferPrecision = bufferPrecision;
For<T>.channelDepth = channelDepth;
For<T>.resourceTextureDescriptionCount = resourceTextureDescriptionCount;
For<T>.resourceTextureDescriptions = resourceTextureDescriptions;
For<T>.d2D1DrawTransformMapperFactory = d2D1DrawTransformMapperFactory;
isInitialized = true;
}
}
this.effectFactory = effectFactory;
this.shaderId = shaderId;
this.constantBufferSize = constantBufferSize;
this.inputCount = inputCount;
this.inputTypes = inputTypes;
this.inputDescriptionCount = inputDescriptionCount;
this.inputDescriptions = inputDescriptions;
this.pixelOptions = pixelOptions;
this.bytecode = bytecode;
this.bytecodeSize = bytecodeSize;
this.bufferPrecision = bufferPrecision;
this.channelDepth = channelDepth;
this.resourceTextureDescriptionCount = resourceTextureDescriptionCount;
this.resourceTextureDescriptions = resourceTextureDescriptions;
}
/// <summary>
/// Gets a reference to the id of the effect.
/// Gets the shader <see cref="For{T}"/> instance.
/// </summary>
public static ref Guid Id
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref shaderId;
}
public static For<T> Instance { get; } = CreateInstance();
/// <summary>
/// Gets the factory for the current effect.
/// Creates a new <see cref="For{T}"/> instance.
/// </summary>
#if NET6_0_OR_GREATER
public static delegate* unmanaged[Stdcall]<IUnknown**, HRESULT> Factory
#else
public static void* Factory
#endif
/// <returns>The initialized <see cref="For{T}"/> instance.</returns>
private static For<T> CreateInstance()
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#if NET6_0_OR_GREATER
get => (delegate* unmanaged[Stdcall]<IUnknown**, HRESULT>)Marshal.GetFunctionPointerForDelegate(EffectFactory);
#else
get => (void*)Marshal.GetFunctionPointerForDelegate(EffectFactory);
#endif
}
// Load all shader properties
Guid shaderId = typeof(T).GUID;
int constantBufferSize = D2D1PixelShader.GetConstantBufferSize<T>();
D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision<T>();
D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth<T>();
D2D1PixelOptions pixelOptions = D2D1PixelShader.GetPixelOptions<T>();
/// <summary>
/// Gets the number of inputs for the effect.
/// </summary>
public static int InputCount => inputCount;
// Prepare the inputs info
int inputCount = D2D1PixelShader.GetInputCount<T>();
D2D1PixelShaderInputType* inputTypes = (D2D1PixelShaderInputType*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), sizeof(D2D1PixelShaderInputType) * inputCount);
/// <summary>
/// Tries to get the effect id, if it has been initialized.
/// </summary>
/// <param name="id">The resulting effect id.</param>
/// <returns>Whether or not the effect had been initialized.</returns>
public static bool TryGetId(out Guid id)
{
lock (typeof(For<T>))
for (int i = 0; i < inputCount; i++)
{
if (isInitialized)
{
id = Id;
return true;
}
inputTypes[i] = D2D1PixelShader.GetInputType<T>(i);
}
id = default;
// Prepare the input descriptions
ReadOnlyMemory<D2D1InputDescription> inputDescriptionsInfo = D2D1PixelShader.GetInputDescriptions<T>();
int inputDescriptionCount = inputDescriptionsInfo.Length;
D2D1InputDescription* inputDescriptions = (D2D1InputDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), sizeof(D2D1InputDescription) * inputDescriptionCount);
return false;
}
inputDescriptionsInfo.Span.CopyTo(new Span<D2D1InputDescription>(inputDescriptions, inputDescriptionCount));
/// <inheritdoc cref="FactoryDelegate"/>
private static int CreateEffect(IUnknown** effectImpl)
{
D2D1TransformMapper? d2D1TransformMapper;
// Prepare the resource texture descriptions
ReadOnlyMemory<D2D1ResourceTextureDescription> resourceTextureDescriptionsInfo = D2D1PixelShader.GetResourceTextureDescriptions<T>();
int resourceTextureDescriptionCount = resourceTextureDescriptionsInfo.Length;
D2D1ResourceTextureDescription* resourceTextureDescriptions = (D2D1ResourceTextureDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), sizeof(D2D1ResourceTextureDescription) * resourceTextureDescriptionCount);
// If there is a custom draw transform factory, run it in a try block and handle exceptions. This
// is needed because the factory will be running user code from a method that's invoked by COM,
// and managed exceptions should never cross the ABI boundary. If it throws, just return the HRESULT.
try
{
ID2D1TransformMapper<T>? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Create();
resourceTextureDescriptionsInfo.Span.CopyTo(new Span<D2D1ResourceTextureDescription>(resourceTextureDescriptions, resourceTextureDescriptionCount));
d2D1TransformMapper = D2D1TransformMapper.For<T>.Get(d2D1DrawTransformMapper);
}
catch (Exception e)
{
*effectImpl = null;
// Copy the bytecode to the target buffer
ReadOnlyMemory<byte> bytecodeInfo = D2D1PixelShader.LoadBytecode<T>();
int bytecodeSize = bytecodeInfo.Length;
byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For<T>), bytecodeSize);
return e.HResult;
}
bytecodeInfo.Span.CopyTo(new Span<byte>(bytecode, bytecodeSize));
return PixelShaderEffect.Factory(
// Initialize the shared instance with the computed state
return new(
CreateEffect,
shaderId,
constantBufferSize,
inputCount,
@@ -279,8 +218,59 @@ internal unsafe partial struct PixelShaderEffect
bufferPrecision,
channelDepth,
resourceTextureDescriptionCount,
resourceTextureDescriptions,
d2D1TransformMapper,
resourceTextureDescriptions);
}
/// <summary>
/// Gets a reference to the id of the effect.
/// </summary>
public ref readonly Guid Id
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref this.shaderId;
}
/// <summary>
/// Gets the factory for the current effect.
/// </summary>
#if NET6_0_OR_GREATER
public delegate* unmanaged[Stdcall]<IUnknown**, HRESULT> Factory
#else
public void* Factory
#endif
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#if NET6_0_OR_GREATER
get => (delegate* unmanaged[Stdcall]<IUnknown**, HRESULT>)Marshal.GetFunctionPointerForDelegate(this.effectFactory);
#else
get => (void*)Marshal.GetFunctionPointerForDelegate(this.effectFactory);
#endif
}
/// <summary>
/// Gets the number of inputs for the effect.
/// </summary>
public int InputCount => this.inputCount;
/// <inheritdoc cref="FactoryDelegate"/>
private static int CreateEffect(IUnknown** effectImpl)
{
For<T> instance = Instance;
return PixelShaderEffect.Factory(
instance.shaderId,
instance.constantBufferSize,
instance.inputCount,
instance.inputTypes,
instance.inputDescriptionCount,
instance.inputDescriptions,
instance.pixelOptions,
instance.bytecode,
instance.bytecodeSize,
instance.bufferPrecision,
instance.channelDepth,
instance.resourceTextureDescriptionCount,
instance.resourceTextureDescriptions,
effectImpl);
}
}
@@ -1,7 +1,7 @@
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if !NET6_0_OR_GREATER
@@ -127,29 +127,14 @@ partial struct PixelShaderEffect
return E.E_INVALIDARG;
}
if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper)
if (@this->d2D1TransformMapper is not null)
{
Rectangle output = outputRect->ToRectangle();
Span<Rectangle> inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectsCount);
// Forward to the current ID2D1TransformMapper instance
HRESULT hresult = @this->d2D1TransformMapper->MapOutputRectToInputRects(outputRect, inputRects, inputRectsCount);
for (int i = 0; i < (int)inputRectsCount; i++)
if (!Windows.SUCCEEDED(hresult))
{
inputs[i] = inputRects[i].ToRectangle();
}
// Invoke MapOutputToInputs and handle exceptions so they don't cross the ABI boundary
try
{
d2D1TransformMapper.MapOutputToInputs(in output, inputs);
}
catch (Exception e)
{
return e.HResult;
}
for (int i = 0; i < (int)inputRectsCount; i++)
{
inputRects[i] = inputs[i].ToRECT();
return hresult;
}
}
else
@@ -189,34 +174,38 @@ partial struct PixelShaderEffect
return E.E_INVALIDARG;
}
if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper)
if (@this->d2D1TransformMapper is not null)
{
Span<Rectangle> inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
Span<Rectangle> opaqueInputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
using ComPtr<D2D1DrawInfoUpdateContextImpl> d2D1DrawInfoUpdateContext = default;
for (int i = 0; i < (int)inputRectCount; i++)
// Create an ID2D1DrawInfoUpdateContext instance
HRESULT hresult = D2D1DrawInfoUpdateContextImpl.Factory(
drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(),
constantBuffer: @this->constantBuffer,
constantBufferSize: @this->constantBufferSize,
d2D1DrawInfo: @this->d2D1DrawInfo);
if (!Windows.SUCCEEDED(hresult))
{
inputs[i] = inputRects[i].ToRectangle();
opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle();
return hresult;
}
ReadOnlySpan<byte> buffer = new(@this->constantBuffer, @this->constantBufferSize);
// Forward the call to the input ID2D1TransformMapper instance
hresult = @this->d2D1TransformMapper->MapInputRectsToOutputRect(
updateContext: (ID2D1DrawInfoUpdateContext*)d2D1DrawInfoUpdateContext.Get(),
inputRects: inputRects,
inputOpaqueSubRects: inputOpaqueSubRects,
inputRectCount: inputRectCount,
outputRect: outputRect,
outputOpaqueSubRect: outputOpaqueSubRect);
Rectangle output;
Rectangle opaqueOutput;
// Regardless of the operation result, always invalidate the context
_ = d2D1DrawInfoUpdateContext.Get()->Close();
// Handle exceptions, as mentioned above
try
if (!Windows.SUCCEEDED(hresult))
{
d2D1TransformMapper.MapInputsToOutput(buffer, inputs, opaqueInputs, out output, out opaqueOutput);
return hresult;
}
catch (Exception e)
{
return e.HResult;
}
*outputRect = output.ToRECT();
*outputOpaqueSubRect = opaqueOutput.ToRECT();
}
else if (inputRectCount == 0)
{
@@ -278,22 +267,15 @@ partial struct PixelShaderEffect
return E.E_INVALIDARG;
}
if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper)
if (@this->d2D1TransformMapper is not null)
{
Rectangle invalidInput = invalidInputRect.ToRectangle();
Rectangle invalidOutput;
// Forward to the current ID2D1TransformMapper instance
HRESULT hresult = @this->d2D1TransformMapper->MapInvalidRect(inputIndex, invalidInputRect, invalidOutputRect);
// Handle exceptions once again
try
if (!Windows.SUCCEEDED(hresult))
{
d2D1TransformMapper.MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput);
return hresult;
}
catch (Exception e)
{
return e.HResult;
}
*invalidOutputRect = invalidOutput.ToRECT();
}
else
{
+144 -7
ファイルの表示
@@ -2,6 +2,7 @@ using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if !NET6_0_OR_GREATER
@@ -31,6 +32,16 @@ unsafe partial struct PixelShaderEffect
/// A cached <see cref="PropertySetFunctionDelegate"/> instance wrapping <see cref="SetConstantBufferImpl"/>.
/// </summary>
private static readonly PropertySetFunctionDelegate SetConstantBufferWrapper = SetConstantBufferImpl;
/// <summary>
/// A cached <see cref="PropertyGetFunctionDelegate"/> instance wrapping <see cref="GetTransformMapperImpl"/>.
/// </summary>
private static readonly PropertyGetFunctionDelegate GetTransformMapperWrapper = GetTransformMapperImpl;
/// <summary>
/// A cached <see cref="PropertySetFunctionDelegate"/> instance wrapping <see cref="SetTransformMapperImpl"/>.
/// </summary>
private static readonly PropertySetFunctionDelegate SetTransformMapperWrapper = SetTransformMapperImpl;
#endif
/// <summary>
@@ -67,6 +78,40 @@ unsafe partial struct PixelShaderEffect
#endif
}
/// <summary>
/// Gets the get accessor for the transform mapper.
/// </summary>
#if NET6_0_OR_GREATER
public static delegate* unmanaged[Stdcall]<IUnknown*, byte*, uint, uint*, int> GetTransformMapper
#else
public static void* GetTransformMapper
#endif
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#if NET6_0_OR_GREATER
get => &GetTransformMapperImpl;
#else
get => (void*)Marshal.GetFunctionPointerForDelegate(GetTransformMapperWrapper);
#endif
}
/// <summary>
/// Gets the set accessor for the transform mapper.
/// </summary>
#if NET6_0_OR_GREATER
public static delegate* unmanaged[Stdcall]<IUnknown*, byte*, uint, int> SetTransformMapper
#else
public static void* SetTransformMapper
#endif
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#if NET6_0_OR_GREATER
get => &SetTransformMapperImpl;
#else
get => (void*)Marshal.GetFunctionPointerForDelegate(SetTransformMapperWrapper);
#endif
}
/// <inheritdoc cref="D2D1_PROPERTY_BINDING.getFunction"/>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static int GetConstantBufferImpl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize)
@@ -119,28 +164,115 @@ unsafe partial struct PixelShaderEffect
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static int SetConstantBufferImpl(IUnknown* effect, byte* data, uint dataSize)
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
if (data is null)
{
return E.E_POINTER;
}
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
if (dataSize != (uint)@this->constantBufferSize)
{
return E.E_INVALIDARG;
}
// Reuse the existing buffer if there is one, otherwise allocate a new one
if (@this->constantBuffer is not null)
{
NativeMemory.Free(@this->constantBuffer);
Buffer.MemoryCopy(data, @this->constantBuffer, dataSize, dataSize);
}
else
{
void* buffer = NativeMemory.Alloc(dataSize);
Buffer.MemoryCopy(data, buffer, dataSize, dataSize);
@this->constantBuffer = (byte*)buffer;
}
void* buffer = NativeMemory.Alloc(dataSize);
return S.S_OK;
}
Buffer.MemoryCopy(data, buffer, dataSize, dataSize);
/// <inheritdoc cref="D2D1_PROPERTY_BINDING.getFunction"/>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static int GetTransformMapperImpl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize)
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
@this->constantBuffer = (byte*)buffer;
if (data is null)
{
return E.E_POINTER;
}
if (dataSize < sizeof(void*))
{
return E.E_INVALIDARG;
}
if (@this->d2D1TransformMapper is null)
{
*(void**)data = null;
}
else
{
HRESULT hresult = ((IUnknown*)@this->d2D1TransformMapper)->QueryInterface(Windows.__uuidof<ID2D1TransformMapper>(), (void**)data);
if (!Windows.SUCCEEDED(hresult))
{
return hresult;
}
}
if (actualSize is not null)
{
*actualSize = (uint)sizeof(void*);
}
return S.S_OK;
}
/// <inheritdoc cref="D2D1_PROPERTY_BINDING.getFunction"/>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
private static int SetTransformMapperImpl(IUnknown* effect, byte* data, uint dataSize)
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
if (data is null)
{
return E.E_POINTER;
}
void* value = *(void**)data;
if (value is null)
{
return E.E_POINTER;
}
if (dataSize != (uint)sizeof(void*))
{
return E.E_INVALIDARG;
}
using ComPtr<IUnknown> unknown = (IUnknown*)value;
using ComPtr<ID2D1TransformMapper> transformMapper = default;
// Check that the input object implements ID2D1TransformMapper
int result = unknown.CopyTo(transformMapper.GetAddressOf());
if (result != S.S_OK)
{
return result;
}
// If there's already an existing manager, release it
if (@this->d2D1TransformMapper is not null)
{
_ = ((IUnknown*)@this->d2D1TransformMapper)->Release();
}
// Store the transform mapper manager into the effect
@this->d2D1TransformMapper = transformMapper.Detach();
return S.S_OK;
}
@@ -172,7 +304,12 @@ unsafe partial struct PixelShaderEffect
using ComPtr<ID2D1ResourceTextureManager> resourceTextureManager = this.resourceTextureManagerBuffer[resourceTextureIndex];
_ = resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data);
HRESULT hresult = resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data);
if (!Windows.SUCCEEDED(hresult))
{
return hresult;
}
if (actualSize is not null)
{
+8 -14
ファイルの表示
@@ -3,6 +3,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if NET6_0_OR_GREATER
@@ -18,14 +19,6 @@ namespace ComputeSharp.D2D1.Interop.Effects;
/// </summary>
internal unsafe partial struct PixelShaderEffect
{
/// <summary>
/// A wrapper for an effect factory.
/// </summary>
/// <param name="effectImpl">The resulting effect factory.</param>
/// <returns>The <c>HRESULT</c> for the operation.</returns>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int FactoryDelegate(IUnknown** effectImpl);
#if !NET6_0_OR_GREATER
/// <inheritdoc cref="QueryInterface"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
@@ -196,9 +189,9 @@ internal unsafe partial struct PixelShaderEffect
private D2D1ResourceTextureDescription* resourceTextureDescriptions;
/// <summary>
/// The handle for the <see cref="D2D1TransformMapper"/> instance in use, if any.
/// The <see cref="ID2D1TransformMapper"/> instance to use, if any.
/// </summary>
private GCHandle d2D1TransformMapperHandle;
private ID2D1TransformMapper* d2D1TransformMapper;
/// <summary>
/// The <see cref="ID2D1DrawInfo"/> instance currently in use.
@@ -231,7 +224,6 @@ internal unsafe partial struct PixelShaderEffect
/// <param name="channelDepth">The channel depth for the resulting output buffer.</param>
/// <param name="resourceTextureDescriptionCount">The number of available resource texture descriptions.</param>
/// <param name="resourceTextureDescriptions">The buffer with the available resource texture descriptions for the shader.</param>
/// <param name="d2D1TransformMapper">The <see cref="D2D1TransformMapper"/> 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(
@@ -248,7 +240,6 @@ internal unsafe partial struct PixelShaderEffect
D2D1ChannelDepth channelDepth,
int resourceTextureDescriptionCount,
D2D1ResourceTextureDescription* resourceTextureDescriptions,
D2D1TransformMapper? d2D1TransformMapper,
IUnknown** effectImpl)
{
PixelShaderEffect* @this;
@@ -283,7 +274,7 @@ internal unsafe partial struct PixelShaderEffect
@this->channelDepth = channelDepth;
@this->resourceTextureDescriptionCount = resourceTextureDescriptionCount;
@this->resourceTextureDescriptions = resourceTextureDescriptions;
@this->d2D1TransformMapperHandle = GCHandle.Alloc(d2D1TransformMapper);
@this->d2D1TransformMapper = null;
@this->d2D1DrawInfo = null;
@this->d2D1EffectContext = null;
@this->resourceTextureManagerBuffer = default;
@@ -347,7 +338,10 @@ internal unsafe partial struct PixelShaderEffect
NativeMemory.Free(this.constantBuffer);
}
this.d2D1TransformMapperHandle.Free();
if (this.d2D1TransformMapper is not null)
{
_ = ((IUnknown*)this.d2D1TransformMapper)->Release();
}
if (this.d2D1DrawInfo is not null)
{
@@ -118,7 +118,7 @@ unsafe partial struct D2D1ResourceTextureManagerImpl
}
/// <summary>
/// The implementation for <c>ID2D1ResourceTextureManager</c>.
/// The implementation for <see cref="ID2D1ResourceTextureManager"/>.
/// </summary>
private static class ID2D1ResourceTextureManagerMethods
{
@@ -13,7 +13,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
partial struct D2D1ResourceTextureManagerImpl
{
/// <summary>
/// The implementation for <c>ID2D1ResourceTextureManagerInternal</c>.
/// The implementation for <see cref="ID2D1ResourceTextureManagerInternal"/>.
/// </summary>
private static unsafe class ID2D1ResourceTextureManagerInternalMethods
{
@@ -13,10 +13,11 @@ using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServ
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
/// <summary>
/// An implementation of the <c>ID2D1ResourceTextureManager</c> and <c>ID2D1ResourceTextureManagerInternal</c> interfaces.
/// An implementation of the <see cref="ID2D1ResourceTextureManager"/> and <see cref="ID2D1ResourceTextureManagerInternal"/> interfaces.
/// </summary>
internal unsafe partial struct D2D1ResourceTextureManagerImpl
{
#if !NET6_0_OR_GREATER
/// <inheritdoc cref="QueryInterface"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int QueryInterfaceDelegate(D2D1ResourceTextureManagerImpl* @this, Guid* riid, void** ppvObject);
@@ -28,21 +29,22 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl
/// <inheritdoc cref="Release"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseDelegate(D2D1ResourceTextureManagerImpl* @this);
#endif
/// <summary>
/// The shared vtable pointer for <see cref="D2D1ResourceTextureManagerImpl"/> instance, for <c>ID2D1ResourceTextureManager</c>.
/// The shared vtable pointer for <see cref="D2D1ResourceTextureManagerImpl"/> instance, for <see cref="ID2D1ResourceTextureManager"/>.
/// </summary>
private static readonly void** VtblForID2D1ResourceTextureManager = InitVtblForID2D1ResourceTextureManagerAndID2D1ResourceTextureManagerInternal();
/// <summary>
/// The shared vtable pointer for <see cref="D2D1ResourceTextureManagerImpl"/> instance, for <c>ID2D1ResourceTextureManagerInternal</c>.
/// The shared vtable pointer for <see cref="D2D1ResourceTextureManagerImpl"/> instance, for <see cref="ID2D1ResourceTextureManagerInternal"/>.
/// </summary>
private static readonly void** VtblForID2D1ResourceTextureManagerInternal = &VtblForID2D1ResourceTextureManager[5];
/// <summary>
/// Initializes the combined vtable for <c>ID2D1ResourceTextureManager</c> and <c>ID2D1ResourceTextureManagerInternal</c>.
/// Initializes the combined vtable for <see cref="ID2D1ResourceTextureManager"/> and <see cref="ID2D1ResourceTextureManagerInternal"/>.
/// </summary>
/// <returns>The combined vtable for <c>ID2D1ResourceTextureManager</c> and <c>ID2D1ResourceTextureManagerInternal</c>.</returns>
/// <returns>The combined vtable for <see cref="ID2D1ResourceTextureManager"/> and <see cref="ID2D1ResourceTextureManagerInternal"/>.</returns>
private static void** InitVtblForID2D1ResourceTextureManagerAndID2D1ResourceTextureManagerInternal()
{
void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1ResourceTextureManagerImpl), sizeof(void*) * 10);
@@ -81,17 +83,17 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl
}
/// <summary>
/// The vtable pointer for the current instance, for <c>ID2D1ResourceTextureManager</c>.
/// The vtable pointer for the current instance, for <see cref="ID2D1ResourceTextureManager"/>.
/// </summary>
private void** lpVtblForID2D1ResourceTextureManager;
/// <summary>
/// The vtable pointer for the current instance, for <c>ID2D1ResourceTextureManagerInternal</c>.
/// The vtable pointer for the current instance, for <see cref="ID2D1ResourceTextureManagerInternal"/>.
/// </summary>
private void** lpVtblForID2D1ResourceTextureManagerInternal;
/// <summary>
/// The current reference count for the object (from <c>IUnknown</c>).
/// The current reference count for the object (from <see cref="IUnknown"/>).
/// </summary>
private volatile int referenceCount;
@@ -15,7 +15,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
internal unsafe struct ID2D1ResourceTextureManager
{
/// <summary>
/// Gets the <see cref="System.Guid"/> for <c>ID2D1ResourceTextureManager</c> (<c>3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64</c>).
/// Gets the <see cref="System.Guid"/> for <see cref="ID2D1ResourceTextureManager"/> (<c>3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64</c>).
/// </summary>
public static ref readonly Guid Guid
{
@@ -54,7 +54,7 @@ internal unsafe struct ID2D1ResourceTextureManager
/// <param name="dataSize">The size, in bytes, of the data.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Initialize(
public HRESULT Initialize(
Guid* resourceId,
D2D1_RESOURCE_TEXTURE_PROPERTIES* resourceTextureProperties,
byte* data,
@@ -81,7 +81,7 @@ internal unsafe struct ID2D1ResourceTextureManager
/// <param name="dataCount">The size of the data buffer to be used to update the resource texture.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Update(
public HRESULT Update(
uint* minimumExtents,
uint* maximimumExtents,
uint* strides,
@@ -15,7 +15,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
internal unsafe struct ID2D1ResourceTextureManagerInternal
{
/// <summary>
/// Gets the <see cref="System.Guid"/> for <c>ID2D1ResourceTextureManagerInternal</c> (<c>5CBB1024-8EA1-4689-81BF-8AD190B5EF5D</c>).
/// Gets the <see cref="System.Guid"/> for <see cref="ID2D1ResourceTextureManagerInternal"/> (<c>5CBB1024-8EA1-4689-81BF-8AD190B5EF5D</c>).
/// </summary>
public static ref readonly Guid Guid
{
@@ -44,13 +44,13 @@ internal unsafe struct ID2D1ResourceTextureManagerInternal
private readonly void** lpVtbl;
/// <summary>
/// Sets the <see cref="ID2D1EffectContext"/> for the current <c>ID2D1ResourceTextureManagerInternal</c> instance.
/// Sets the <see cref="ID2D1EffectContext"/> for the current <see cref="ID2D1ResourceTextureManagerInternal"/> instance.
/// </summary>
/// <param name="effectContext">The input <see cref="ID2D1EffectContext"/> for the manager.</param>
/// <param name="dimensions">A pointer to an optional amount of dimensions for the target resource texture, for validation.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Initialize(ID2D1EffectContext* effectContext, uint* dimensions)
public HRESULT Initialize(ID2D1EffectContext* effectContext, uint* dimensions)
{
return ((delegate* unmanaged[Stdcall]<ID2D1ResourceTextureManagerInternal*, ID2D1EffectContext*, uint*, int>)this.lpVtbl[3])(
(ID2D1ResourceTextureManagerInternal*)Unsafe.AsPointer(ref this),
@@ -64,7 +64,7 @@ internal unsafe struct ID2D1ResourceTextureManagerInternal
/// <param name="resourceTexture">The resulting <see cref="ID2D1ResourceTexture"/> instance.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetResourceTexture(ID2D1ResourceTexture** resourceTexture)
public HRESULT GetResourceTexture(ID2D1ResourceTexture** resourceTexture)
{
return ((delegate* unmanaged[Stdcall]<ID2D1ResourceTextureManagerInternal*, ID2D1ResourceTexture**, int>)this.lpVtbl[4])(
(ID2D1ResourceTextureManagerInternal*)Unsafe.AsPointer(ref this),
@@ -0,0 +1,166 @@
using System;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
#if !NET6_0_OR_GREATER
using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute;
#endif
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
/// <inheritdoc/>
partial struct D2D1DrawInfoUpdateContextImpl
{
/// <summary>
/// The implementation for <see cref="ID2D1DrawInfoUpdateContext"/>.
/// </summary>
private static unsafe class ID2D1DrawInfoUpdateContextMethods
{
#if !NET6_0_OR_GREATER
/// <inheritdoc cref="GetConstantBufferSize"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int GetConstantBufferSizeDelegate(D2D1DrawInfoUpdateContextImpl* @this, uint* size);
/// <inheritdoc cref="GetConstantBuffer"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int GetConstantBufferDelegate(D2D1DrawInfoUpdateContextImpl* @this, byte* buffer, uint bufferCount);
/// <inheritdoc cref="SetConstantBuffer"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int SetConstantBufferDelegate(D2D1DrawInfoUpdateContextImpl* @this, byte* buffer, uint bufferCount);
/// <summary>
/// A cached <see cref="QueryInterfaceDelegate"/> instance wrapping <see cref="QueryInterface"/>.
/// </summary>
public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface;
/// <summary>
/// A cached <see cref="AddRefDelegate"/> instance wrapping <see cref="AddRef"/>.
/// </summary>
public static readonly AddRefDelegate AddRefWrapper = AddRef;
/// <summary>
/// A cached <see cref="ReleaseDelegate"/> instance wrapping <see cref="Release"/>.
/// </summary>
public static readonly ReleaseDelegate ReleaseWrapper = Release;
/// <summary>
/// A cached <see cref="GetConstantBufferSizeDelegate"/> instance wrapping <see cref="GetConstantBufferSize"/>.
/// </summary>
public static readonly GetConstantBufferSizeDelegate GetConstantBufferSizeWrapper = GetConstantBufferSize;
/// <summary>
/// A cached <see cref="GetConstantBufferDelegate"/> instance wrapping <see cref="GetConstantBuffer"/>.
/// </summary>
public static readonly GetConstantBufferDelegate GetConstantBufferWrapper = GetConstantBuffer;
/// <summary>
/// A cached <see cref="SetConstantBufferDelegate"/> instance wrapping <see cref="SetConstantBuffer"/>.
/// </summary>
public static readonly SetConstantBufferDelegate SetConstantBufferWrapper = SetConstantBuffer;
#endif
/// <inheritdoc cref="D2D1DrawInfoUpdateContextImpl.QueryInterface"/>
[UnmanagedCallersOnly]
public static int QueryInterface(D2D1DrawInfoUpdateContextImpl* @this, Guid* riid, void** ppvObject)
{
return @this->QueryInterface(riid, ppvObject);
}
/// <inheritdoc cref="D2D1DrawInfoUpdateContextImpl.AddRef"/>
[UnmanagedCallersOnly]
public static uint AddRef(D2D1DrawInfoUpdateContextImpl* @this)
{
return @this->AddRef();
}
/// <inheritdoc cref="D2D1DrawInfoUpdateContextImpl.Release"/>
[UnmanagedCallersOnly]
public static uint Release(D2D1DrawInfoUpdateContextImpl* @this)
{
return @this->Release();
}
/// <inheritdoc cref="ID2D1DrawInfoUpdateContext.GetConstantBufferSize"/>
[UnmanagedCallersOnly]
public static int GetConstantBufferSize(D2D1DrawInfoUpdateContextImpl* @this, uint* size)
{
if (size is null)
{
return E.E_POINTER;
}
if (@this->d2D1DrawInfo is null)
{
return RO.RO_E_CLOSED;
}
*size = (uint)@this->constantBufferSize;
return S.S_OK;
}
/// <inheritdoc cref="ID2D1DrawInfoUpdateContext.GetConstantBuffer"/>
[UnmanagedCallersOnly]
public static int GetConstantBuffer(D2D1DrawInfoUpdateContextImpl* @this, byte* buffer, uint bufferCount)
{
if (buffer is null)
{
return E.E_POINTER;
}
if (bufferCount < @this->constantBufferSize)
{
return E.E_NOT_SUFFICIENT_BUFFER;
}
if (@this->constantBuffer is null)
{
return E.E_NOT_VALID_STATE;
}
if (@this->d2D1DrawInfo is null)
{
return RO.RO_E_CLOSED;
}
if (@this->constantBufferSize > 0)
{
Buffer.MemoryCopy(@this->constantBuffer, buffer, bufferCount, @this->constantBufferSize);
}
return S.S_OK;
}
/// <inheritdoc cref="ID2D1DrawInfoUpdateContext.SetConstantBuffer"/>
[UnmanagedCallersOnly]
public static int SetConstantBuffer(D2D1DrawInfoUpdateContextImpl* @this, byte* buffer, uint bufferCount)
{
if (buffer is null)
{
return E.E_POINTER;
}
if (bufferCount != (uint)@this->constantBufferSize)
{
return E.E_INVALIDARG;
}
if (@this->d2D1DrawInfo is null)
{
return RO.RO_E_CLOSED;
}
// If the buffer is empty, just do nothing
if (bufferCount == 0)
{
return S.S_OK;
}
// Copy the buffer to the backing store, so the effect can also access it later
Buffer.MemoryCopy(buffer, @this->constantBuffer, bufferCount, bufferCount);
// Propagate it to the ID2D1DrawInfo object in use as well
return @this->d2D1DrawInfo->SetPixelShaderConstantBuffer(buffer, bufferCount);
}
}
}
@@ -0,0 +1,88 @@
using System;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
#if !NET6_0_OR_GREATER
using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute;
#endif
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
/// <inheritdoc/>
unsafe partial struct D2D1DrawInfoUpdateContextImpl
{
/// <inheritdoc cref="ID2D1DrawInfoUpdateContextInternal.Close"/>
public int Close()
{
this.d2D1DrawInfo = null;
return S.S_OK;
}
/// <summary>
/// The implementation for <see cref="ID2D1DrawInfoUpdateContextInternal"/>.
/// </summary>
private static class ID2D1DrawInfoUpdateContextInternalMethods
{
#if !NET6_0_OR_GREATER
/// <inheritdoc cref="Close"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate int CloseDelegate(D2D1DrawInfoUpdateContextImpl* @this);
/// <summary>
/// A cached <see cref="QueryInterfaceDelegate"/> instance wrapping <see cref="QueryInterface"/>.
/// </summary>
public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface;
/// <summary>
/// A cached <see cref="AddRefDelegate"/> instance wrapping <see cref="AddRef"/>.
/// </summary>
public static readonly AddRefDelegate AddRefWrapper = AddRef;
/// <summary>
/// A cached <see cref="ReleaseDelegate"/> instance wrapping <see cref="Release"/>.
/// </summary>
public static readonly ReleaseDelegate ReleaseWrapper = Release;
/// <summary>
/// A cached <see cref="CloseDelegate"/> instance wrapping <see cref="Close"/>.
/// </summary>
public static readonly CloseDelegate CloseWrapper = Close;
#endif
/// <inheritdoc cref="D2D1DrawInfoUpdateContextImpl.QueryInterface"/>
[UnmanagedCallersOnly]
public static int QueryInterface(D2D1DrawInfoUpdateContextImpl* @this, Guid* riid, void** ppvObject)
{
@this = (D2D1DrawInfoUpdateContextImpl*)&((void**)@this)[-1];
return @this->QueryInterface(riid, ppvObject);
}
/// <inheritdoc cref="D2D1DrawInfoUpdateContextImpl.AddRef"/>
[UnmanagedCallersOnly]
public static uint AddRef(D2D1DrawInfoUpdateContextImpl* @this)
{
@this = (D2D1DrawInfoUpdateContextImpl*)&((void**)@this)[-1];
return @this->AddRef();
}
/// <inheritdoc cref="D2D1DrawInfoUpdateContextImpl.Release"/>
[UnmanagedCallersOnly]
public static uint Release(D2D1DrawInfoUpdateContextImpl* @this)
{
@this = (D2D1DrawInfoUpdateContextImpl*)&((void**)@this)[-1];
return @this->Release();
}
/// <inheritdoc cref="ID2D1DrawInfoUpdateContextInternal.Close"/>
[UnmanagedCallersOnly]
public static int Close(D2D1DrawInfoUpdateContextImpl* @this)
{
@this = (D2D1DrawInfoUpdateContextImpl*)&((void**)@this)[-1];
return @this->Close();
}
}
}
@@ -0,0 +1,206 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if NET6_0_OR_GREATER
using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers;
#else
using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
#endif
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
/// <summary>
/// An implementation of the <see cref="ID2D1DrawInfoUpdateContext"/> and <see cref="ID2D1DrawInfoUpdateContextInternal"/> interfaces.
/// </summary>
internal unsafe partial struct D2D1DrawInfoUpdateContextImpl
{
#if !NET6_0_OR_GREATER
/// <inheritdoc cref="QueryInterface"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int QueryInterfaceDelegate(D2D1DrawInfoUpdateContextImpl* @this, Guid* riid, void** ppvObject);
/// <inheritdoc cref="AddRef"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint AddRefDelegate(D2D1DrawInfoUpdateContextImpl* @this);
/// <inheritdoc cref="Release"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseDelegate(D2D1DrawInfoUpdateContextImpl* @this);
#endif
/// <summary>
/// The shared vtable pointer for <see cref="D2D1DrawInfoUpdateContextImpl"/> instance, for <see cref="ID2D1DrawInfoUpdateContext"/>.
/// </summary>
private static readonly void** VtblForID2D1DrawInfoUpdateContext = InitVtblForID2D1DrawInfoUpdateContextAndID2D1DrawInfoUpdateContextInternal();
/// <summary>
/// The shared vtable pointer for <see cref="D2D1DrawInfoUpdateContextImpl"/> instance, for <see cref="ID2D1DrawInfoUpdateContextInternal"/>.
/// </summary>
private static readonly void** VtblForID2D1DrawInfoUpdateContextInternal = &VtblForID2D1DrawInfoUpdateContext[5];
/// <summary>
/// Initializes the combined vtable for <see cref="ID2D1DrawInfoUpdateContext"/> and <see cref="ID2D1DrawInfoUpdateContextInternal"/>.
/// </summary>
/// <returns>The combined vtable for <see cref="ID2D1DrawInfoUpdateContext"/> and <see cref="ID2D1DrawInfoUpdateContextInternal"/>.</returns>
private static void** InitVtblForID2D1DrawInfoUpdateContextAndID2D1DrawInfoUpdateContextInternal()
{
void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1DrawInfoUpdateContextImpl), sizeof(void*) * 10);
// ID2D1ResourceTextureManager
#if NET6_0_OR_GREATER
lpVtbl[0] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, Guid*, void**, int>)&ID2D1DrawInfoUpdateContextMethods.QueryInterface;
lpVtbl[1] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, uint>)&ID2D1DrawInfoUpdateContextMethods.AddRef;
lpVtbl[2] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, uint>)&ID2D1DrawInfoUpdateContextMethods.Release;
lpVtbl[3] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, uint*, int>)&ID2D1DrawInfoUpdateContextMethods.GetConstantBufferSize;
lpVtbl[4] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, byte*, uint, int>)&ID2D1DrawInfoUpdateContextMethods.GetConstantBuffer;
lpVtbl[5] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, byte*, uint, int>)&ID2D1DrawInfoUpdateContextMethods.SetConstantBuffer;
#else
lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.QueryInterfaceWrapper);
lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.AddRefWrapper);
lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.ReleaseWrapper);
lpVtbl[3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.GetConstantBufferSizeWrapper);
lpVtbl[4] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.GetConstantBufferWrapper);
lpVtbl[5] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextMethods.SetConstantBufferWrapper);
#endif
// ID2D1ResourceTextureManagerInternal
#if NET6_0_OR_GREATER
lpVtbl[6 + 0] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, Guid*, void**, int>)&ID2D1DrawInfoUpdateContextInternalMethods.QueryInterface;
lpVtbl[6 + 1] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, uint>)&ID2D1DrawInfoUpdateContextInternalMethods.AddRef;
lpVtbl[6 + 2] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, uint>)&ID2D1DrawInfoUpdateContextInternalMethods.Release;
lpVtbl[6 + 3] = (delegate* unmanaged<D2D1DrawInfoUpdateContextImpl*, int>)&ID2D1DrawInfoUpdateContextInternalMethods.Close;
#else
lpVtbl[6 + 0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextInternalMethods.QueryInterfaceWrapper);
lpVtbl[6 + 1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextInternalMethods.AddRefWrapper);
lpVtbl[6 + 2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextInternalMethods.ReleaseWrapper);
lpVtbl[6 + 3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1DrawInfoUpdateContextInternalMethods.CloseWrapper);
#endif
return lpVtbl;
}
/// <summary>
/// The vtable pointer for the current instance, for <see cref="ID2D1DrawInfoUpdateContext"/>.
/// </summary>
private void** lpVtblForID2D1DrawInfoUpdateContext;
/// <summary>
/// The vtable pointer for the current instance, for <see cref="ID2D1DrawInfoUpdateContextInternal"/>.
/// </summary>
private void** lpVtblForID2D1DrawInfoUpdateContextInternal;
/// <summary>
/// The current reference count for the object (from <see cref="IUnknown"/>).
/// </summary>
private volatile int referenceCount;
/// <summary>
/// The constant buffer data, if set.
/// </summary>
private byte* constantBuffer;
/// <summary>
/// The size of <see cref="constantBuffer"/>.
/// </summary>
private int constantBufferSize;
/// <summary>
/// The <see cref="ID2D1DrawInfo"/> instance currently in use.
/// </summary>
private ID2D1DrawInfo* d2D1DrawInfo;
/// <summary>
/// The factory method for <see cref="D2D1DrawInfoUpdateContextImpl"/> instances.
/// </summary>
/// <param name="drawInfoUpdateContext">The resulting draw info update context instance.</param>
/// <param name="constantBuffer">The constant buffer data, if set.</param>
/// <param name="constantBufferSize">The size of <paramref name="constantBuffer"/>.</param>
/// <param name="d2D1DrawInfo">The <see cref="ID2D1DrawInfo"/> instance currently in use.</param>
/// <returns>This always returns <c>0</c>.</returns>
public static HRESULT Factory(
D2D1DrawInfoUpdateContextImpl** drawInfoUpdateContext,
byte* constantBuffer,
int constantBufferSize,
ID2D1DrawInfo* d2D1DrawInfo)
{
D2D1DrawInfoUpdateContextImpl* @this;
try
{
@this = (D2D1DrawInfoUpdateContextImpl*)NativeMemory.Alloc((nuint)sizeof(D2D1DrawInfoUpdateContextImpl));
}
catch (OutOfMemoryException)
{
*drawInfoUpdateContext = null;
return E.E_OUTOFMEMORY;
}
@this->lpVtblForID2D1DrawInfoUpdateContext = VtblForID2D1DrawInfoUpdateContext;
@this->lpVtblForID2D1DrawInfoUpdateContextInternal = VtblForID2D1DrawInfoUpdateContextInternal;
@this->referenceCount = 1;
@this->constantBuffer = constantBuffer;
@this->constantBufferSize = constantBufferSize;
@this->d2D1DrawInfo = d2D1DrawInfo;
*drawInfoUpdateContext = @this;
return S.S_OK;
}
/// <inheritdoc cref="IUnknown.QueryInterface"/>
public int QueryInterface(Guid* riid, void** ppvObject)
{
if (ppvObject is null)
{
return E.E_POINTER;
}
// ID2D1DrawInfoUpdateContext
if (riid->Equals(Windows.__uuidof<IUnknown>()) ||
riid->Equals(ID2D1DrawInfoUpdateContext.Guid))
{
_ = Interlocked.Increment(ref this.referenceCount);
*ppvObject = Unsafe.AsPointer(ref this);
return S.S_OK;
}
// ID2D1DrawInfoUpdateContextInternal
if (riid->Equals(ID2D1DrawInfoUpdateContextInternal.Guid))
{
_ = Interlocked.Increment(ref this.referenceCount);
*ppvObject = (void**)Unsafe.AsPointer(ref this) + 1;
return S.S_OK;
}
*ppvObject = null;
return E.E_NOINTERFACE;
}
/// <inheritdoc cref="IUnknown.AddRef"/>
public uint AddRef()
{
return (uint)Interlocked.Increment(ref this.referenceCount);
}
/// <inheritdoc cref="IUnknown.Release"/>
public uint Release()
{
uint referenceCount = (uint)Interlocked.Decrement(ref this.referenceCount);
if (referenceCount == 0)
{
NativeMemory.Free(Unsafe.AsPointer(ref this));
}
return referenceCount;
}
}
@@ -0,0 +1,143 @@
using System;
using System.Drawing;
using System.Runtime.CompilerServices;
#if NET6_0_OR_GREATER
using System.Runtime.InteropServices;
#endif
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Interop.Effects;
using TerraFX.Interop.Windows;
#if !NET6_0_OR_GREATER
using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute;
#endif
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
/// <inheritdoc/>
unsafe partial struct D2D1TransformMapperImpl
{
/// <inheritdoc cref="QueryInterface(Guid*, void**)"/>
[UnmanagedCallersOnly]
private static int QueryInterface(D2D1TransformMapperImpl* @this, Guid* riid, void** ppvObject)
{
return @this->QueryInterface(riid, ppvObject);
}
/// <inheritdoc cref="AddRef()"/>
[UnmanagedCallersOnly]
private static uint AddRef(D2D1TransformMapperImpl* @this)
{
return @this->AddRef();
}
/// <inheritdoc cref="Release()"/>
[UnmanagedCallersOnly]
private static uint Release(D2D1TransformMapperImpl* @this)
{
return @this->Release();
}
/// <inheritdoc cref="ID2D1TransformMapper.MapInputRectsToOutputRect"/>
[UnmanagedCallersOnly]
private static int MapInputRectsToOutputRect(
D2D1TransformMapperImpl* @this,
ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext,
RECT* inputRects,
RECT* inputOpaqueSubRects,
uint inputRectCount,
RECT* outputRect,
RECT* outputOpaqueSubRect)
{
Span<Rectangle> inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
Span<Rectangle> opaqueInputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
for (int i = 0; i < (int)inputRectCount; i++)
{
inputs[i] = inputRects[i].ToRectangle();
opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle();
}
Rectangle output;
Rectangle opaqueOutput;
// Invoke MapInputsToOutput and handle exceptions so they don't cross the ABI boundary
try
{
Unsafe.As<ID2D1TransformMapperInterop>(@this->transformMapperHandle.Target!).MapInputsToOutput(
d2D1DrawInfoUpdateContext,
inputs,
opaqueInputs,
out output,
out opaqueOutput);
}
catch (Exception e)
{
return e.HResult;
}
*outputRect = output.ToRECT();
*outputOpaqueSubRect = opaqueOutput.ToRECT();
return S.S_OK;
}
/// <inheritdoc cref="ID2D1TransformMapper.MapOutputRectToInputRects"/>
[UnmanagedCallersOnly]
private static int MapOutputRectToInputRects(
D2D1TransformMapperImpl* @this,
RECT* outputRect,
RECT* inputRects,
uint inputRectsCount)
{
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();
}
// Handle exceptions, as mentioned above
try
{
Unsafe.As<ID2D1TransformMapperInterop>(@this->transformMapperHandle.Target!).MapOutputToInputs(in output, inputs);
}
catch (Exception e)
{
return e.HResult;
}
for (int i = 0; i < (int)inputRectsCount; i++)
{
inputRects[i] = inputs[i].ToRECT();
}
return S.S_OK;
}
/// <inheritdoc cref="ID2D1TransformMapper.MapInvalidRect"/>
[UnmanagedCallersOnly]
private static int MapInvalidRect(
D2D1TransformMapperImpl* @this,
uint inputIndex,
RECT invalidInputRect,
RECT* invalidOutputRect)
{
Rectangle invalidInput = invalidInputRect.ToRectangle();
Rectangle invalidOutput;
// Handle exceptions once again
try
{
Unsafe.As<ID2D1TransformMapperInterop>(@this->transformMapperHandle.Target!).MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput);
}
catch (Exception e)
{
return e.HResult;
}
*invalidOutputRect = invalidOutput.ToRECT();
return S.S_OK;
}
}
@@ -0,0 +1,296 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using ComputeSharp.D2D1.Interop.Effects;
using TerraFX.Interop.Windows;
#if NET6_0_OR_GREATER
using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers;
#else
using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers;
#endif
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
/// <summary>
/// An implementation of the <see cref="ID2D1TransformMapper"/> interface wrapping <see cref="ID2D1TransformMapperInterop"/>.
/// </summary>
internal unsafe partial struct D2D1TransformMapperImpl
{
#if !NET6_0_OR_GREATER
/// <inheritdoc cref="IUnknown.QueryInterface"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int QueryInterfaceDelegate(D2D1TransformMapperImpl* @this, Guid* riid, void** ppvObject);
/// <inheritdoc cref="IUnknown.AddRef"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint AddRefDelegate(D2D1TransformMapperImpl* @this);
/// <inheritdoc cref="IUnknown.Release"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseDelegate(D2D1TransformMapperImpl* @this);
/// <inheritdoc cref="ID2D1TransformMapper.MapInputRectsToOutputRect"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int MapInputRectsToOutputRectDelegate(
D2D1TransformMapperImpl* @this,
ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext,
RECT* inputRects,
RECT* inputOpaqueSubRects,
uint inputRectCount,
RECT* outputRect,
RECT* outputOpaqueSubRect);
/// <inheritdoc cref="ID2D1TransformMapper.MapOutputRectToInputRects"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int MapOutputRectToInputRectsDelegate(
D2D1TransformMapperImpl* @this,
RECT* outputRect,
RECT* inputRects,
uint inputRectsCount);
/// <inheritdoc cref="ID2D1TransformMapper.MapInvalidRect"/>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int MapInvalidRectDelegate(
D2D1TransformMapperImpl* @this,
uint inputIndex,
RECT invalidInputRect,
RECT* invalidOutputRect);
/// <summary>
/// A cached <see cref="QueryInterfaceDelegate"/> instance wrapping <see cref="QueryInterface(Guid*, void**)"/>.
/// </summary>
private static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface;
/// <summary>
/// A cached <see cref="AddRefDelegate"/> instance wrapping <see cref="AddRef()"/>.
/// </summary>
private static readonly AddRefDelegate AddRefWrapper = AddRef;
/// <summary>
/// A cached <see cref="ReleaseDelegate"/> instance wrapping <see cref="Release()"/>.
/// </summary>
private static readonly ReleaseDelegate ReleaseWrapper = Release;
/// <summary>
/// A cached <see cref="MapInputRectsToOutputRectDelegate"/> instance wrapping <see cref="MapInputRectsToOutputRect"/>.
/// </summary>
private static readonly MapInputRectsToOutputRectDelegate MapInputRectsToOutputRectWrapper = MapInputRectsToOutputRect;
/// <summary>
/// A cached <see cref="MapOutputRectToInputRectsDelegate"/> instance wrapping <see cref="MapOutputRectToInputRects"/>.
/// </summary>
private static readonly MapOutputRectToInputRectsDelegate MapOutputRectToInputRectsWrapper = MapOutputRectToInputRects;
/// <summary>
/// A cached <see cref="MapInvalidRectDelegate"/> instance wrapping <see cref="MapInvalidRect"/>.
/// </summary>
private static readonly MapInvalidRectDelegate MapInvalidRectWrapper = MapInvalidRect;
#endif
/// <summary>
/// The shared method table pointer for all <see cref="ID2D1TransformMapper"/> instances.
/// </summary>
private static readonly void** Vtbl = InitVtbl();
/// <summary>
/// Builds the custom method table pointer for <see cref="ID2D1TransformMapper"/>.
/// </summary>
/// <returns>The method table pointer for <see cref="ID2D1TransformMapper"/>.</returns>
private static void** InitVtbl()
{
void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1TransformMapperImpl), sizeof(void*) * 6);
#if NET6_0_OR_GREATER
lpVtbl[0] = (delegate* unmanaged<D2D1TransformMapperImpl*, Guid*, void**, int>)&QueryInterface;
lpVtbl[1] = (delegate* unmanaged<D2D1TransformMapperImpl*, uint>)&AddRef;
lpVtbl[2] = (delegate* unmanaged<D2D1TransformMapperImpl*, uint>)&Release;
lpVtbl[3] = (delegate* unmanaged<D2D1TransformMapperImpl*, ID2D1DrawInfoUpdateContext*, RECT*, RECT*, uint, RECT*, RECT*, int>)&MapInputRectsToOutputRect;
lpVtbl[4] = (delegate* unmanaged<D2D1TransformMapperImpl*, RECT*, RECT*, uint, int>)&MapOutputRectToInputRects;
lpVtbl[5] = (delegate* unmanaged<D2D1TransformMapperImpl*, uint, RECT, RECT*, int>)&MapInvalidRect;
#else
lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(QueryInterfaceWrapper);
lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(AddRefWrapper);
lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ReleaseWrapper);
lpVtbl[3] = (void*)Marshal.GetFunctionPointerForDelegate(MapInputRectsToOutputRectWrapper);
lpVtbl[4] = (void*)Marshal.GetFunctionPointerForDelegate(MapOutputRectToInputRectsWrapper);
lpVtbl[5] = (void*)Marshal.GetFunctionPointerForDelegate(MapInvalidRectWrapper);
#endif
return lpVtbl;
}
/// <summary>
/// The vtable pointer for the current instance.
/// </summary>
private void** lpVtbl;
/// <summary>
/// The current reference count for the object (from <see cref="IUnknown"/>).
/// </summary>
private volatile int referenceCount;
/// <summary>
/// A <see cref="GCHandle"/> to the wrapped <see cref="ID2D1TransformMapperInterop"/> instance.
/// </summary>
private GCHandle transformMapperHandle;
/// <summary>
/// The <see cref="System.Threading.SpinLock"/> instance to synchronize accesses to this instance.
/// </summary>
private SpinLock spinLock;
/// <summary>
/// The factory method for <see cref="D2D1TransformMapperImpl"/> instances.
/// </summary>
/// <param name="transformMapper">The input <see cref="ID2D1TransformMapperInterop"/> instance to wrap.</param>
/// <param name="d2D1TransformMapperProxy">The resulting <see cref="D2D1TransformMapperImpl"/> instance.</param>
public static void Factory(
ID2D1TransformMapperInterop transformMapper,
D2D1TransformMapperImpl** d2D1TransformMapperProxy)
{
D2D1TransformMapperImpl* @this = (D2D1TransformMapperImpl*)NativeMemory.Alloc((nuint)sizeof(D2D1TransformMapperImpl));
@this->lpVtbl = Vtbl;
@this->referenceCount = 1;
@this->transformMapperHandle = GCHandle.Alloc(transformMapper);
@this->spinLock = new SpinLock(enableThreadOwnerTracking: false);
*d2D1TransformMapperProxy = @this;
}
/// <summary>
/// Gets a reference to the <see cref="System.Threading.SpinLock"/> instance used to synchronize reference counts.
/// </summary>
[UnscopedRef]
public ref SpinLock SpinLock => ref this.spinLock;
/// <summary>
/// Ensures the target of the current CCW is tracked and is keeping it alive.
/// </summary>
/// <param name="target">The associated <see cref="ID2D1TransformMapperInterop"/> object to track.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnsureTargetIsTracked(ID2D1TransformMapperInterop target)
{
this.transformMapperHandle.Target = target;
}
/// <summary>
/// Copies the current object onto a target pointer.
/// </summary>
/// <param name="transformMapper">The target <see cref="ID2D1TransformMapper"/> pointer.</param>
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
/// <remarks>This method must only be called if the caller has taken a lock on <see cref="SpinLock"/> already.</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyToWithNoLock(ID2D1TransformMapper** transformMapper)
{
this.referenceCount++;
*transformMapper = (ID2D1TransformMapper*)Unsafe.AsPointer(ref this);
}
/// <inheritdoc cref="IUnknown.QueryInterface"/>
/// <remarks>
/// <para>This method is the same as <see cref="QueryInterface(Guid*, void**)"/> but skips locks.</para>
/// <para>This method must only be called if the caller has taken a lock on <see cref="SpinLock"/> already.</para>
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int QueryInterfaceWithNoLock(Guid* riid, void** ppvObject)
{
if (ppvObject is null)
{
return E.E_POINTER;
}
if (riid->Equals(Windows.__uuidof<IUnknown>()) ||
riid->Equals(ID2D1TransformMapper.Guid))
{
this.referenceCount++;
*ppvObject = Unsafe.AsPointer(ref this);
return S.S_OK;
}
*ppvObject = null;
return E.E_NOINTERFACE;
}
/// <inheritdoc cref="IUnknown.QueryInterface"/>
private int QueryInterface(Guid* riid, void** ppvObject)
{
bool lockTaken = false;
this.spinLock.Enter(ref lockTaken);
try
{
return QueryInterfaceWithNoLock(riid, ppvObject);
}
finally
{
this.spinLock.Exit();
}
}
/// <inheritdoc cref="IUnknown.AddRef"/>
private uint AddRef()
{
bool lockTaken = false;
this.spinLock.Enter(ref lockTaken);
try
{
return (uint)++this.referenceCount;
}
finally
{
this.spinLock.Exit();
}
}
/// <inheritdoc cref="IUnknown.Release"/>
private uint Release()
{
bool lockTaken = false;
this.spinLock.Enter(ref lockTaken);
uint referenceCount;
try
{
referenceCount = (uint)--this.referenceCount;
// There are two special cases to consider here:
// - If the reference count is 1, it means that the D2D1TransformMapper<T> object is the only
// thing keeping this CCW alive. In that case, we can reset the GC handle pointing back to it,
// so that it can be collected if nobody else is referencing it. This breaks the reference cycle
// between the two object, which would have otherwise caused them to remain alive forever.
// - If the reference count is 0, the object is simply being destroyed. This is moved outside of
// this try/finally block, as otherwise accessing the lock from the finally block would write to
// out of bounds memory (as the field is in native memory that has just been freed).
if (referenceCount == 1)
{
this.transformMapperHandle.Target = null;
}
}
finally
{
this.spinLock.Exit();
}
// Destroy the object if this was the last reference left (see notes above as to why this is here)
if (referenceCount == 0)
{
this.transformMapperHandle.Free();
NativeMemory.Free(Unsafe.AsPointer(ref this));
}
return referenceCount;
}
}
@@ -0,0 +1,87 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
#pragma warning disable CS0649
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
/// <summary>
/// The updater for <see cref="TerraFX.Interop.DirectX.ID2D1DrawInfo"/> type to use with built-in effects.
/// </summary>
[Guid("430C5B40-AE16-485F-90E6-4FA4915144B6")]
internal unsafe struct ID2D1DrawInfoUpdateContext
{
/// <summary>
/// Gets the <see cref="System.Guid"/> for <see cref="ID2D1DrawInfoUpdateContext"/> (<c>430C5B40-AE16-485F-90E6-4FA4915144B6</c>).
/// </summary>
public static ref readonly Guid Guid
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x40, 0x5B, 0x0C, 0x43,
0x16, 0xAE,
0x5F, 0x48,
0x90, 0xE6,
0x4F,
0xA4,
0x91,
0x51,
0x44,
0xB6
};
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
/// <summary>
/// The vtable for the current instance.
/// </summary>
private readonly void** lpVtbl;
/// <summary>
/// Retrieves the size of the constant buffer for the current effect.
/// </summary>
/// <param name="size">The resulting size of the constant buffer.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT GetConstantBufferSize(uint* size)
{
return ((delegate* unmanaged[Stdcall]<ID2D1DrawInfoUpdateContext*, uint*, int>)this.lpVtbl[3])(
(ID2D1DrawInfoUpdateContext*)Unsafe.AsPointer(ref this),
size);
}
/// <summary>
/// Retrieves the constant buffer data for the current effect.
/// </summary>
/// <param name="buffer">A pointer to the buffer to fill with the constant buffer data.</param>
/// <param name="bufferCount">The size of the buffer provided through <paramref name="buffer"/>.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT GetConstantBuffer(byte* buffer, uint bufferCount)
{
return ((delegate* unmanaged[Stdcall]<ID2D1DrawInfoUpdateContext*, byte*, uint, int>)this.lpVtbl[4])(
(ID2D1DrawInfoUpdateContext*)Unsafe.AsPointer(ref this),
buffer,
bufferCount);
}
/// <summary>
/// Sets the constant buffer data for the current effect.
/// </summary>
/// <param name="buffer">A pointer to the constant buffer data to use to update the effect.</param>
/// <param name="bufferCount">The size of the buffer provided through <paramref name="buffer"/>.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT SetConstantBuffer(byte* buffer, uint bufferCount)
{
return ((delegate* unmanaged[Stdcall]<ID2D1DrawInfoUpdateContext*, byte*, uint, int>)this.lpVtbl[5])(
(ID2D1DrawInfoUpdateContext*)Unsafe.AsPointer(ref this),
buffer,
bufferCount);
}
}
@@ -0,0 +1,54 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
#pragma warning disable CS0649
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
/// <summary>
/// An internal version of <see cref="ID2D1DrawInfoUpdateContext"/> that supports being closed, to manage lifetime scopes.
/// </summary>
[Guid("CF2F5BB0-3F5E-4D6E-8FF1-D9A7EB6C0250")]
internal unsafe struct ID2D1DrawInfoUpdateContextInternal
{
/// <summary>
/// Gets the <see cref="System.Guid"/> for <see cref="ID2D1DrawInfoUpdateContextInternal"/> (<c>CF2F5BB0-3F5E-4D6E-8FF1-D9A7EB6C0250</c>).
/// </summary>
public static ref readonly Guid Guid
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xB0, 0x5B, 0x2F, 0xCF,
0x5E, 0x3F,
0x6E, 0x4D,
0x8F, 0xF1,
0xD9,
0xA7,
0xEB,
0x6C,
0x02,
0x50
};
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
/// <summary>
/// The vtable for the current instance.
/// </summary>
private readonly void** lpVtbl;
/// <summary>
/// Closes the current instance.
/// </summary>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT Close()
{
return ((delegate* unmanaged[Stdcall]<ID2D1DrawInfoUpdateContext*, int>)this.lpVtbl[3])((ID2D1DrawInfoUpdateContext*)Unsafe.AsPointer(ref this));
}
}
@@ -0,0 +1,113 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
#pragma warning disable CS0649
namespace ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
/// <summary>
/// The transform mapper manager type to use with built-in effects.
/// </summary>
[Guid("02E6D48D-B892-4FBC-AA54-119203BAB802")]
internal unsafe struct ID2D1TransformMapper
{
/// <summary>
/// Gets the <see cref="System.Guid"/> for <see cref="ID2D1TransformMapper"/> (<c>02E6D48D-B892-4FBC-AA54-119203BAB802</c>).
/// </summary>
public static ref readonly Guid Guid
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x8D, 0xD4, 0xE6, 0x02,
0x92, 0xB8,
0xBC, 0x4F,
0xAA, 0x54,
0x11,
0x92,
0x03,
0xBA,
0xB8,
0x02
};
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
/// <summary>
/// The vtable for the current instance.
/// </summary>
private readonly void** lpVtbl;
/// <summary>
/// Performs the inverse mapping to <see cref="MapOutputRectToInputRects(RECT*, RECT*, uint)"/>.
/// </summary>
/// <param name="updateContext">The input <see cref="ID2D1DrawInfoUpdateContext"/> instance.</param>
/// <param name="inputRects">An array of input rectangles to be mapped to the output rectangle.</param>
/// <param name="inputOpaqueSubRects">An array of input rectangles to be mapped to the opaque output rectangle.</param>
/// <param name="inputRectCount">The number of inputs specified.</param>
/// <param name="outputRect">The output rectangle that maps to the corresponding input rectangle.</param>
/// <param name="outputOpaqueSubRect">The output rectangle that maps to the corresponding opaque input rectangle.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT MapInputRectsToOutputRect(
ID2D1DrawInfoUpdateContext* updateContext,
RECT* inputRects,
RECT* inputOpaqueSubRects,
uint inputRectCount,
RECT* outputRect,
RECT* outputOpaqueSubRect)
{
return ((delegate* unmanaged[Stdcall]<ID2D1TransformMapper*, ID2D1DrawInfoUpdateContext*, RECT*, RECT*, uint, RECT*, RECT*, int>)this.lpVtbl[3])(
(ID2D1TransformMapper*)Unsafe.AsPointer(ref this),
updateContext,
inputRects,
inputOpaqueSubRects,
inputRectCount,
outputRect,
outputOpaqueSubRect);
}
/// <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="outputRect">The output rectangle from which the inputs must be mapped.</param>
/// <param name="inputRects">The corresponding set of inputs. The inputs will directly correspond to the transform inputs.</param>
/// <param name="inputRectsCount">The number of inputs specified.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT MapOutputRectToInputRects(
RECT* outputRect,
RECT* inputRects,
uint inputRectsCount)
{
return ((delegate* unmanaged[Stdcall]<ID2D1TransformMapper*, RECT*, RECT*, uint, int>)this.lpVtbl[4])(
(ID2D1TransformMapper*)Unsafe.AsPointer(ref this),
outputRect,
inputRects,
inputRectsCount);
}
/// <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="invalidInputRect">The invalid input rectangle.</param>
/// <param name="invalidOutputRect">The output rectangle to which the input rectangle must be mapped.</param>
/// <returns>An <see cref="HRESULT"/> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT MapInvalidRect(
uint inputIndex,
RECT invalidInputRect,
RECT* invalidOutputRect)
{
return ((delegate* unmanaged[Stdcall]<ID2D1TransformMapper*, uint, RECT, RECT*, int>)this.lpVtbl[5])(
(ID2D1TransformMapper*)Unsafe.AsPointer(ref this),
inputIndex,
invalidInputRect,
invalidOutputRect);
}
}
@@ -1,24 +0,0 @@
namespace ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract;
/// <summary>
/// A base type for a transform mapper factory to be used in a D2D1 pixel shader effect.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader associated to the transform mapper.</typeparam>
/// <typeparam name="TParameters">The type of parameters that the transform mapper will use.</typeparam>
/// <typeparam name="TTransformMapper">The type of concrete transform mapper to produce from this factory.</typeparam>
internal abstract class D2D1TransformMapperFactory<T, TParameters, TTransformMapper> : ID2D1TransformMapperFactory<T>
where T : unmanaged, ID2D1PixelShader
where TParameters : unmanaged
where TTransformMapper : D2D1TransformMapper<T, TParameters>, new()
{
/// <inheritdoc/>
ID2D1TransformMapper<T> ID2D1TransformMapperFactory<T>.Create()
{
return new TTransformMapper { ParametersAccessor = ParametersAccessor };
}
/// <summary>
/// The <see cref="D2D1TransformMapperParametersAccessor{T, TParameters}"/> instance to use to retrieve parameters for the transform mapper.
/// </summary>
public required D2D1TransformMapperParametersAccessor<T, TParameters> ParametersAccessor { get; init; }
}
@@ -1,16 +0,0 @@
namespace ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract;
/// <summary>
/// A base type for an accessor of parameters to be used in D2D1 transform mapping implementations.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader associated to the transform mapper.</typeparam>
/// <typeparam name="TParameters">The type of parameters that the transform mapper will use.</typeparam>
internal abstract class D2D1TransformMapperParametersAccessor<T, TParameters>
{
/// <summary>
/// Gets the parameters to be used by the transform mapper.
/// </summary>
/// <param name="shader">The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties).</param>
/// <returns>The resulting parameters to be used by the transform mapper.</returns>
public abstract TParameters Get(in T shader);
}
@@ -1,11 +1,9 @@
using System;
using System.Drawing;
using System.Runtime.CompilerServices;
using ComputeSharp.D2D1.Interop.Effects;
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Shaders.Interop.Helpers;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract;
/// <summary>
@@ -13,7 +11,7 @@ namespace ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract;
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader associated to the transform mapper.</typeparam>
/// <typeparam name="TParameters">The type of parameters that the transform mapper will use.</typeparam>
internal abstract class D2D1TransformMapper<T, TParameters> : D2D1TransformMapper, ID2D1TransformMapper<T>
internal abstract class D2D1TransformMapper<T, TParameters> : D2D1TransformMapper<T>
where T : unmanaged, ID2D1PixelShader
where TParameters : unmanaged
{
@@ -22,57 +20,15 @@ internal abstract class D2D1TransformMapper<T, TParameters> : D2D1TransformMappe
/// </summary>
private TParameters parameters;
/// <inheritdoc cref="D2D1TransformMapperFactory{T, TParameters, TTransformMapper}.ParametersAccessor"/>
public D2D1TransformMapperParametersAccessor<T, TParameters>? ParametersAccessor { get; init; }
/// <summary>
/// Transforms an input rectangle to an output rectangle.
/// </summary>
/// <param name="parameters">The parameters to be used to inform the transformation.</param>
/// <param name="rectangle">The input rectangle to transform to output.</param>
protected abstract void TransformInputToOutput(in TParameters parameters, ref Rectangle64 rectangle);
/// <summary>
/// Transforms an output rectangle to an input rectangle.
/// </summary>
/// <param name="parameters">The parameters to be used to inform the transformation.</param>
/// <param name="rectangle">The output rectangle to transform to input.</param>
protected abstract void TransformOutputToInput(in TParameters parameters, ref Rectangle64 rectangle);
/// <inheritdoc/>
public override void MapInputsToOutput(ReadOnlySpan<byte> buffer, ReadOnlySpan<Rectangle> inputs, ReadOnlySpan<Rectangle> opaqueInputs, out Rectangle output, out Rectangle opaqueOutput)
public override void MapInputsToOutput(
D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext,
ReadOnlySpan<Rectangle> inputs,
ReadOnlySpan<Rectangle> opaqueInputs,
out Rectangle output,
out Rectangle opaqueOutput)
{
Unsafe.SkipInit(out T shader);
shader.InitializeFromDispatchData(buffer);
MapInputsToOutput(in shader, inputs, opaqueInputs, out output, out opaqueOutput);
}
/// <inheritdoc/>
public override void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs)
{
Rectangle64 output64 = Rectangle64.FromRectangle(output);
TransformOutputToInput(in this.parameters, ref output64);
inputs.Fill(output64.ToRectangleWithD2D1LogicallyInfiniteClamping());
}
/// <inheritdoc/>
public override void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput)
{
Rectangle64 output64 = Rectangle64.FromRectangle(invalidInput);
TransformInputToOutput(in this.parameters, ref output64);
invalidOutput = output64.ToRectangleWithD2D1LogicallyInfiniteClamping();
}
/// <inheritdoc/>
public void MapInputsToOutput(in T shader, ReadOnlySpan<Rectangle> inputs, ReadOnlySpan<Rectangle> opaqueInputs, out Rectangle output, out Rectangle opaqueOutput)
{
this.parameters = ParametersAccessor!.Get(in shader);
this.parameters = GetParameters(drawInfoUpdateContext);
if (inputs.IsEmpty)
{
@@ -96,4 +52,44 @@ internal abstract class D2D1TransformMapper<T, TParameters> : D2D1TransformMappe
opaqueOutput = Rectangle.Empty;
}
}
/// <inheritdoc/>
public override void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs)
{
Rectangle64 output64 = Rectangle64.FromRectangle(output);
TransformOutputToInput(in this.parameters, ref output64);
inputs.Fill(output64.ToRectangleWithD2D1LogicallyInfiniteClamping());
}
/// <inheritdoc/>
public override void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput)
{
Rectangle64 output64 = Rectangle64.FromRectangle(invalidInput);
TransformInputToOutput(in this.parameters, ref output64);
invalidOutput = output64.ToRectangleWithD2D1LogicallyInfiniteClamping();
}
/// <summary>
/// Gets the <typeparamref name="TParameters"/> values for the current transform mapper.
/// </summary>
/// <param name="drawInfoUpdateContext">The input <see cref="D2D1DrawInfoUpdateContext{T}"/> value, which can be used to access and modify shader data.</param>
protected abstract TParameters GetParameters(D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext);
/// <summary>
/// Transforms an input rectangle to an output rectangle.
/// </summary>
/// <param name="parameters">The parameters to be used to inform the transformation.</param>
/// <param name="rectangle">The input rectangle to transform to output.</param>
protected abstract void TransformInputToOutput(in TParameters parameters, ref Rectangle64 rectangle);
/// <summary>
/// Transforms an output rectangle to an input rectangle.
/// </summary>
/// <param name="parameters">The parameters to be used to inform the transformation.</param>
/// <param name="rectangle">The output rectangle to transform to input.</param>
protected abstract void TransformOutputToInput(in TParameters parameters, ref Rectangle64 rectangle);
}
@@ -8,19 +8,19 @@ using ComputeSharp.D2D1.Shaders.Interop.Helpers;
namespace ComputeSharp.D2D1.Shaders.Interop.Factories;
/// <summary>
/// A container for shader-specific affine transform mapper factory.
/// Shared helpers for <see cref="D2D1AffineTransformMapper{T}"/>.
/// </summary>
/// <remarks>
/// This non-generic type is used so that <see cref="Transform"/> and <see cref="SubtractAndClampToMaxIfOverflow"/> are not recompiled for each generic type instantiation.
/// </remarks>
internal sealed class D2D1AffineTransformMapperFactory
file static class D2D1AffineTransformMapper
{
/// <summary>
/// Transforms a target rectangle using a given transform matrix.
/// </summary>
/// <param name="matrix">The transform matrix to use.</param>
/// <param name="rectangle">The rectangle to transform.</param>
private static void Transform(in Matrix3x2 matrix, ref Rectangle64 rectangle)
public static void Transform(in Matrix3x2 matrix, ref Rectangle64 rectangle)
{
// Get the rectangle corners
Point64 topLeft = new(rectangle.Left, rectangle.Top);
@@ -60,7 +60,7 @@ internal sealed class D2D1AffineTransformMapperFactory
/// <param name="y">The value to subtract.</param>
/// <returns>The result of the subtraction, clamped to <see cref="long.MaxValue"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static long SubtractAndClampToMaxIfOverflow(long x, long y)
public static long SubtractAndClampToMaxIfOverflow(long x, long y)
{
long z = unchecked(x - y);
@@ -73,74 +73,68 @@ internal sealed class D2D1AffineTransformMapperFactory
return z;
}
}
/// <summary>
/// A custom <see cref="D2D1TransformMapper{T, TParameters}"/> implementation for an affine transform.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader associated to the transform mapper.</typeparam>
internal abstract class D2D1AffineTransformMapper<T> : D2D1TransformMapper<T, Matrix3x2>
where T : unmanaged, ID2D1PixelShader
{
/// <inheritdoc/>
protected sealed override void TransformInputToOutput(in Matrix3x2 parameters, ref Rectangle64 rectangle)
{
D2D1AffineTransformMapper.Transform(in parameters, ref rectangle);
}
/// <inheritdoc/>
protected sealed override void TransformOutputToInput(in Matrix3x2 parameters, ref Rectangle64 rectangle)
{
if (!Matrix3x2.Invert(parameters, out Matrix3x2 matrix))
{
static void Throw()
{
throw new ArgumentException("The input transform matrix can't be inverted, so it can't be used for a transform mapper.");
}
Throw();
}
D2D1AffineTransformMapper.Transform(in matrix, ref rectangle);
}
/// <summary>
/// A custom <see cref="D2D1TransformMapperFactory{T, TParameters, TTransformMapper}"/> implementation for an affine transform.
/// A <see cref="D2D1AffineTransformMapper{T}"/> implementation for a constant affine transform matrix.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader associated to the transform mapper.</typeparam>
public sealed class For<T> : D2D1TransformMapperFactory<T, Matrix3x2, For<T>.TransformMapper>
where T : unmanaged, ID2D1PixelShader
public sealed class ConstantMatrix : D2D1AffineTransformMapper<T>
{
/// <summary>
/// A <see cref="D2D1TransformMapperParametersAccessor{T, TParameters}"/> implementation for a constant affine transform matrix.
/// Gets the fixed affine transform matrix.
/// </summary>
public sealed class ConstantMatrix : D2D1TransformMapperParametersAccessor<T, Matrix3x2>
{
/// <summary>
/// Gets the fixed affine transform matrix.
/// </summary>
public Matrix3x2 Amount { get; init; }
public required Matrix3x2 Amount { get; init; }
/// <inheritdoc/>
public override Matrix3x2 Get(in T shader)
{
return Amount;
}
/// <inheritdoc/>
protected override Matrix3x2 GetParameters(D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext)
{
return Amount;
}
}
/// <summary>
/// A <see cref="D2D1AffineTransformMapper{T}"/> implementation for a dynamic affine transform matrix.
/// </summary>
public sealed class DynamicMatrix : D2D1AffineTransformMapper<T>
{
/// <summary>
/// A <see cref="D2D1TransformMapperParametersAccessor{T, TParameters}"/> implementation for a dynamic affine transform matrix.
/// Gets the <see cref="D2D1TransformMapperFactory{T}.Accessor{TResult}"/> instance to get the dynamic affine transform matrix.
/// </summary>
public sealed class DynamicMatrix : D2D1TransformMapperParametersAccessor<T, Matrix3x2>
public required D2D1TransformMapperFactory<T>.Accessor<Matrix3x2> Accessor { get; init; }
/// <inheritdoc/>
protected override Matrix3x2 GetParameters(D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext)
{
/// <summary>
/// Gets the <see cref="D2D1TransformMapperFactory{T}.Accessor{TResult}"/> instance to get the dynamic affine transform matrix.
/// </summary>
public required D2D1TransformMapperFactory<T>.Accessor<Matrix3x2> Accessor { get; init; }
/// <inheritdoc/>
public override Matrix3x2 Get(in T shader)
{
return Accessor(in shader);
}
}
/// <summary>
/// A custom <see cref="D2D1TransformMapper{T, TParameters}"/> implementation for an affine transform.
/// </summary>
public sealed class TransformMapper : D2D1TransformMapper<T, Matrix3x2>
{
/// <inheritdoc/>
protected override void TransformInputToOutput(in Matrix3x2 parameters, ref Rectangle64 rectangle)
{
Transform(in parameters, ref rectangle);
}
/// <inheritdoc/>
protected override void TransformOutputToInput(in Matrix3x2 parameters, ref Rectangle64 rectangle)
{
if (!Matrix3x2.Invert(parameters, out Matrix3x2 matrix))
{
static void Throw()
{
throw new ArgumentException("The input transform matrix can't be inverted, so it can't be used for a transform mapper.");
}
Throw();
}
Transform(in matrix, ref rectangle);
}
return Accessor(drawInfoUpdateContext.GetConstantBuffer());
}
}
}
-116
ファイルの表示
@@ -1,116 +0,0 @@
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract;
using ComputeSharp.D2D1.Shaders.Interop.Helpers;
namespace ComputeSharp.D2D1.Shaders.Interop.Factories;
/// <summary>
/// A custom <see cref="D2D1TransformMapperFactory{T, TParameters, TTransformMapper}"/> implementation for an inflate transform.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader associated to the transform mapper.</typeparam>
internal sealed class D2D1InflateTransformMapperFactory<T> : D2D1TransformMapperFactory<T, (int, int, int, int), D2D1InflateTransformMapperFactory<T>.TransformMapper>
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// A <see cref="D2D1TransformMapperParametersAccessor{T, TParameters}"/> implementation for a constant inflate amount.
/// </summary>
public sealed class ConstantAmount : D2D1TransformMapperParametersAccessor<T, (int, int, int, int)>
{
/// <summary>
/// Gets the fixed inflate amount.
/// </summary>
public int Amount { get; init; }
/// <inheritdoc/>
public override (int, int, int, int) Get(in T shader)
{
return (Amount, Amount, Amount, Amount);
}
}
/// <summary>
/// A <see cref="D2D1TransformMapperParametersAccessor{T, TParameters}"/> implementation for a constant inflate LTRB amount.
/// </summary>
public sealed class ConstantLeftTopRightBottomAmount : D2D1TransformMapperParametersAccessor<T, (int, int, int, int)>
{
/// <summary>
/// The constant left inflate amount.
/// </summary>
public int Left { get; init; }
/// <summary>
/// The constant top inflate amount.
/// </summary>
public int Top { get; init; }
/// <summary>
/// The constant right inflate amount.
/// </summary>
public int Right { get; init; }
/// <summary>
/// The constant bottom inflate amount.
/// </summary>
public int Bottom { get; init; }
/// <inheritdoc/>
public override (int, int, int, int) Get(in T shader)
{
return (Left, Top, Right, Bottom);
}
}
/// <summary>
/// A <see cref="D2D1TransformMapperParametersAccessor{T, TParameters}"/> implementation for a dynamic inflate amount.
/// </summary>
public sealed class DynamicAmount : D2D1TransformMapperParametersAccessor<T, (int, int, int, int)>
{
/// <summary>
/// Gets the <see cref="D2D1TransformMapperFactory{T}.Accessor{TResult}"/> instance to get the dynamic inflate amount.
/// </summary>
public required D2D1TransformMapperFactory<T>.Accessor<int> Accessor { get; init; }
/// <inheritdoc/>
public override (int, int, int, int) Get(in T shader)
{
int amount = Accessor!(in shader);
return (amount, amount, amount, amount);
}
}
/// <summary>
/// A <see cref="D2D1TransformMapperParametersAccessor{T, TParameters}"/> implementation for a dynamic inflate LTRB amount.
/// </summary>
public sealed class DynamicLeftTopRightBottomAmount : D2D1TransformMapperParametersAccessor<T, (int, int, int, int)>
{
/// <summary>
/// Gets the <see cref="D2D1TransformMapperFactory{T}.Accessor{TResult}"/> instance to get the dynamic inflate LTRB amount.
/// </summary>
public required D2D1TransformMapperFactory<T>.Accessor<(int, int, int, int)> Accessor { get; init; }
/// <inheritdoc/>
public override (int, int, int, int) Get(in T shader)
{
return Accessor!(in shader);
}
}
/// <summary>
/// A custom <see cref="D2D1TransformMapper{T, TParameters}"/> implementation for an inflate transform.
/// </summary>
public sealed class TransformMapper : D2D1TransformMapper<T, (int Left, int Top, int Right, int Bottom)>
{
/// <inheritdoc/>
protected override void TransformInputToOutput(in (int Left, int Top, int Right, int Bottom) parameters, ref Rectangle64 rectangle)
{
rectangle.Inflate(parameters.Left, parameters.Top, parameters.Right, parameters.Bottom);
}
/// <inheritdoc/>
protected override void TransformOutputToInput(in (int Left, int Top, int Right, int Bottom) parameters, ref Rectangle64 rectangle)
{
rectangle.Inflate(parameters.Left, parameters.Top, parameters.Right, parameters.Bottom);
}
}
}
+110
ファイルの表示
@@ -0,0 +1,110 @@
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Shaders.Interop.Factories.Abstract;
using ComputeSharp.D2D1.Shaders.Interop.Helpers;
namespace ComputeSharp.D2D1.Shaders.Interop.Factories;
/// <summary>
/// A custom <see cref="D2D1TransformMapper{T, TParameters}"/> implementation for an inflate transform.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader associated to the transform mapper.</typeparam>
internal abstract class D2D1InflateTransformMapper<T> : D2D1TransformMapper<T, (int Left, int Top, int Right, int Bottom)>
where T : unmanaged, ID2D1PixelShader
{
/// <inheritdoc/>
protected sealed override void TransformInputToOutput(in (int Left, int Top, int Right, int Bottom) parameters, ref Rectangle64 rectangle)
{
rectangle.Inflate(parameters.Left, parameters.Top, parameters.Right, parameters.Bottom);
}
/// <inheritdoc/>
protected sealed override void TransformOutputToInput(in (int Left, int Top, int Right, int Bottom) parameters, ref Rectangle64 rectangle)
{
rectangle.Inflate(parameters.Left, parameters.Top, parameters.Right, parameters.Bottom);
}
/// <summary>
/// A <see cref="D2D1InflateTransformMapper{T}"/> implementation for a constant inflate amount.
/// </summary>
public sealed class ConstantAmount : D2D1InflateTransformMapper<T>
{
/// <summary>
/// Gets the fixed inflate amount.
/// </summary>
public required int Amount { get; init; }
/// <inheritdoc/>
protected override (int Left, int Top, int Right, int Bottom) GetParameters(D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext)
{
return (Amount, Amount, Amount, Amount);
}
}
/// <summary>
/// A <see cref="D2D1TransformMapper{T, TParameters}"/> implementation for a constant inflate LTRB amount.
/// </summary>
public sealed class ConstantLeftTopRightBottomAmount : D2D1InflateTransformMapper<T>
{
/// <summary>
/// The constant left inflate amount.
/// </summary>
public required int Left { get; init; }
/// <summary>
/// The constant top inflate amount.
/// </summary>
public required int Top { get; init; }
/// <summary>
/// The constant right inflate amount.
/// </summary>
public required int Right { get; init; }
/// <summary>
/// The constant bottom inflate amount.
/// </summary>
public required int Bottom { get; init; }
/// <inheritdoc/>
protected override (int Left, int Top, int Right, int Bottom) GetParameters(D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext)
{
return (Left, Top, Right, Bottom);
}
}
/// <summary>
/// A <see cref="D2D1TransformMapper{T, TParameters}"/> implementation for a dynamic inflate amount.
/// </summary>
public sealed class DynamicAmount : D2D1InflateTransformMapper<T>
{
/// <summary>
/// Gets the <see cref="D2D1TransformMapperFactory{T}.Accessor{TResult}"/> instance to get the dynamic inflate amount.
/// </summary>
public required D2D1TransformMapperFactory<T>.Accessor<int> Accessor { get; init; }
/// <inheritdoc/>
protected override (int Left, int Top, int Right, int Bottom) GetParameters(D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext)
{
int amount = Accessor(drawInfoUpdateContext.GetConstantBuffer());
return (amount, amount, amount, amount);
}
}
/// <summary>
/// A <see cref="D2D1TransformMapper{T, TParameters}"/> implementation for a dynamic inflate LTRB amount.
/// </summary>
public sealed class DynamicLeftTopRightBottomAmount : D2D1InflateTransformMapper<T>
{
/// <summary>
/// Gets the <see cref="D2D1TransformMapperFactory{T}.Accessor{TResult}"/> instance to get the dynamic inflate LTRB amount.
/// </summary>
public required D2D1TransformMapperFactory<T>.Accessor<(int, int, int, int)> Accessor { get; init; }
/// <inheritdoc/>
protected override (int Left, int Top, int Right, int Bottom) GetParameters(D2D1DrawInfoUpdateContext<T> drawInfoUpdateContext)
{
return Accessor(drawInfoUpdateContext.GetConstantBuffer());
}
}
}
+3 -2
ファイルの表示
@@ -2,6 +2,7 @@ using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.Extensions;
using TerraFX.Interop.DirectX;
#pragma warning disable CS0618
@@ -31,8 +32,8 @@ internal readonly unsafe struct D2D1DrawInfoDispatchDataLoader : ID2D1DispatchDa
/// <inheritdoc/>
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<byte> data)
{
_ = this.d2D1DrawInfo->SetPixelShaderConstantBuffer(
this.d2D1DrawInfo->SetPixelShaderConstantBuffer(
buffer: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)),
bufferCount: (uint)data.Length);
bufferCount: (uint)data.Length).Assert();
}
}
@@ -0,0 +1,39 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.Shaders.Loaders;
/// <summary>
/// A data loader for D2D1 pixel shaders to be passed onto an <see cref="ID2D1DrawInfoUpdateContext"/> object.
/// </summary>
internal readonly unsafe struct D2D1DrawInfoUpdateContextDispatchDataLoader : ID2D1DispatchDataLoader
{
/// <summary>
/// The <see cref="ID2D1DrawInfoUpdateContext"/> object in use.
/// </summary>
private readonly ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext;
/// <summary>
/// Creates a new <see cref="D2D1DrawInfoUpdateContextDispatchDataLoader"/> instance.
/// </summary>
/// <param name="d2D1DrawInfoUpdateContext">The <see cref="ID2D1DrawInfoUpdateContext"/> object to use.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal D2D1DrawInfoUpdateContextDispatchDataLoader(ID2D1DrawInfoUpdateContext* d2D1DrawInfoUpdateContext)
{
this.d2D1DrawInfoUpdateContext = d2D1DrawInfoUpdateContext;
}
/// <inheritdoc/>
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<byte> data)
{
this.d2D1DrawInfoUpdateContext->SetConstantBuffer(
buffer: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)),
bufferCount: (uint)data.Length).Assert();
}
}
+1
ファイルの表示
@@ -63,6 +63,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Windows\shared\windef\RECT.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Windows\shared\winerror\D2DERR.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Windows\shared\winerror\E.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Windows\shared\winerror\RO.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Windows\shared\winerror\Windows.cs" />
</ItemGroup>
</Project>
+12
ファイルの表示
@@ -0,0 +1,12 @@
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from shared/winerror.h in the Windows SDK for Windows 10.0.22621.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
internal static partial class RO
{
[NativeTypeName("#define RO_E_CLOSED _HRESULT_TYPEDEF_(0x80000013L)")]
public const int RO_E_CLOSED = unchecked((int)(0x80000013));
}
バイナリファイルは表示されません。

変更後

幅:  |  高さ:  |  サイズ: 2.0 MiB

+3
ファイルの表示
@@ -95,6 +95,9 @@
<None Include="..\ComputeSharp.Tests\Assets\TerracedHills.png" Link="Assets\TerracedHills.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Assets\RadialFadeOut.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="..\..\samples\ComputeSharp.SwapChain\Textures\RustyMetal.png" Link="Assets\Textures\RustyMetal.png" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
+5 -1
ファイルの表示
@@ -17,7 +17,7 @@ public partial class D2D1EffectRegistrationDataTests
Assert.AreEqual(effectId, data.ClassId);
Assert.AreEqual(2, data.NumberOfInputs);
Assert.IsTrue(data.EffectFactory is not null);
Assert.AreEqual(17, data.PropertyBindings.Length);
Assert.AreEqual(18, data.PropertyBindings.Length);
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ConstantBuffer), data.PropertyBindings.Span[0].PropertyName);
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager0), data.PropertyBindings.Span[1].PropertyName);
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager1), data.PropertyBindings.Span[2].PropertyName);
@@ -35,6 +35,7 @@ public partial class D2D1EffectRegistrationDataTests
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager13), data.PropertyBindings.Span[14].PropertyName);
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager14), data.PropertyBindings.Span[15].PropertyName);
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.ResourceTextureManager15), data.PropertyBindings.Span[16].PropertyName);
Assert.AreEqual(nameof(D2D1PixelShaderEffectProperty.TransformMapper), data.PropertyBindings.Span[17].PropertyName);
foreach (ref readonly D2D1PropertyBinding propertyBinding in data.PropertyBindings.Span)
{
@@ -104,6 +105,9 @@ public partial class D2D1EffectRegistrationDataTests
<Property name='ResourceTextureManager15' type='iunknown'>
<Property name='DisplayName' type='string' value='ResourceTextureManager15'/>
</Property>
<Property name='TransformMapper' type='iunknown'>
<Property name='DisplayName' type='string' value='TransformMapper'/>
</Property>
</Effect>
""", data.PropertyXml);
}
+17 -35
ファイルの表示
@@ -1,6 +1,5 @@
using System;
using System.ComponentModel;
using System.Drawing;
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Tests.Effects;
using ComputeSharp.D2D1.Tests.Helpers;
@@ -23,42 +22,11 @@ public partial class D2D1PixelShaderEffectTests
D2D1PixelShaderEffect.RegisterForD2D1Factory1<InvertEffect>(null, out _);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
public unsafe void RegisterForD2D1Factory1_WithTransformMapper_NullD2D1Factory1()
{
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyTransformMapper.Shader, DummyTransformMapper>(null, out _);
}
public sealed partial class DummyTransformMapper : ID2D1TransformMapper<DummyTransformMapper.Shader>
{
public void MapInputsToOutput(in Shader shader, ReadOnlySpan<Rectangle> inputs, ReadOnlySpan<Rectangle> opaqueInputs, out Rectangle output, out Rectangle opaqueOutput)
{
output = default;
opaqueOutput = default;
}
public void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput)
{
invalidOutput = default;
}
public void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs)
{
}
[D2DInputCount(0)]
public partial struct Shader : ID2D1PixelShader
{
public float4 Execute() => default;
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
public unsafe void RegisterForD2D1Factory1_WithTransformMapperFactory_NullD2D1Factory1()
{
D2D1PixelShaderEffect.RegisterForD2D1Factory1<PixelateEffect>(null, null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<PixelateEffect>(null, out _);
}
[TestMethod]
@@ -117,6 +85,20 @@ public partial class D2D1PixelShaderEffectTests
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect((void*)1, (D2D1ResourceTextureManager)null!, 0);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
public unsafe void SetTransformMapperForD2D1Effect_RCW_NullD2D1Effect()
{
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(null, (void*)1);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
public unsafe void SetTransformMapperForD2D1Effect_RCW_NullD2D1ResourceTextureManager()
{
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect((void*)1, (D2D1TransformMapper<NullConstantBufferShader>)null!);
}
[TestMethod]
[ExpectedException(typeof(Win32Exception))]
public unsafe void NullConstantBuffer_DrawImageFails()
@@ -125,7 +107,7 @@ public partial class D2D1PixelShaderEffectTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<NullConstantBufferShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<NullConstantBufferShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -156,7 +138,7 @@ public partial class D2D1PixelShaderEffectTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ConstantBufferSizeTestShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ConstantBufferSizeTestShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
+11 -11
ファイルの表示
@@ -108,7 +108,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyShaderWithResourceTexture>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyShaderWithResourceTexture>(d2D1Factory2.Get(), out _);
using ComPtr<IUnknown> resourceTextureManager = default;
@@ -152,7 +152,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyShaderWithResourceTexture>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyShaderWithResourceTexture>(d2D1Factory2.Get(), out _);
D2D1ResourceTextureManager resourceTextureManager = new(
extents: stackalloc uint[] { 128, 128 },
@@ -192,7 +192,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -251,7 +251,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -315,7 +315,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -373,7 +373,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom2DResourceTextureShader>(d2D1Factory2.Get(), out _);
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
string wallpaper0Path = Path.Combine(assemblyPath, "Assets", "Wallpaper0.png");
@@ -480,7 +480,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom3DResourceTextureShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<IndexFrom3DResourceTextureShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -567,7 +567,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture1DShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture1DShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -655,7 +655,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture2DShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture2DShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -758,7 +758,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture3DShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<CopyFromResourceTexture3DShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -854,7 +854,7 @@ public partial class D2D1ResourceTextureManagerTests
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<NullResourceTextureShader>(d2D1Factory2.Get(), null, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<NullResourceTextureShader>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
+227
ファイルの表示
@@ -0,0 +1,227 @@
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Tests.Helpers;
using ComputeSharp.D2D1.Tests.Shaders;
using ComputeSharp.Tests.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Win32;
using Win32.Graphics.Direct2D;
#pragma warning disable CS0649, IDE0044, IDE0065
namespace ComputeSharp.D2D1.Tests;
using D2D1_MAPPED_RECT = MappedRect;
using Rectangle = System.Drawing.Rectangle;
[TestClass]
[TestCategory("D2D1TransformMapper")]
public partial class D2D1TransformMapperTests
{
[TestMethod]
public unsafe void VerifyInterfaces()
{
D2D1TransformMapper<HelloWorld> transformMapper = D2D1TransformMapperFactory<HelloWorld>.Inflate(4);
using ComPtr<IUnknown> unknown = default;
using ComPtr<IUnknown> transformMapper2 = default;
Guid uuidOfIUnknown = typeof(IUnknown).GUID;
Guid uuidOfTransformMapper = new("02E6D48D-B892-4FBC-AA54-119203BAB802");
// The object implements IUnknown and the transform mapper interface
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf()));
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapper, out *(IntPtr*)transformMapper2.GetAddressOf()));
Assert.IsTrue(unknown.Get() is not null);
Assert.IsTrue(transformMapper2.Get() is not null);
using ComPtr<IUnknown> garbage = default;
Guid uuidOfGarbage = Guid.NewGuid();
// Any other random QueryInterface should fail
Assert.AreEqual(CustomQueryInterfaceResult.Failed, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfGarbage, out *(IntPtr*)garbage.GetAddressOf()));
Assert.IsTrue(garbage.Get() is null);
}
[TestMethod]
public unsafe void VerifyReferenceCounting()
{
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<DummyShader>(d2D1Factory2.Get(), out _);
D2D1TransformMapper<HelloWorld> transformMapper = D2D1TransformMapperFactory<HelloWorld>.Inflate(4);
using ComPtr<IUnknown> transformMapper2 = default;
Guid uuidOfTransformMapper = new("02E6D48D-B892-4FBC-AA54-119203BAB802");
Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)transformMapper).GetInterface(ref uuidOfTransformMapper, out *(IntPtr*)transformMapper2.GetAddressOf()));
_ = transformMapper2.Get()->AddRef();
// Right after creation, the transform mapper has only 2 ref count (one is the managed object, one is this ComPtr<T>)
Assert.AreEqual(2u, transformMapper2.Get()->Release());
using (ComPtr<ID2D1Effect> d2D1Effect = default)
{
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<DummyShader>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
_ = transformMapper2.Get()->AddRef();
// After setting a transform mapper to an effect, the count raises to 3
Assert.AreEqual(3u, transformMapper2.Get()->Release());
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
_ = transformMapper2.Get()->AddRef();
// Adding the same transform mapper again doesn't increment ref count
Assert.AreEqual(3u, transformMapper2.Get()->Release());
}
_ = transformMapper2.Get()->AddRef();
// If the effect is released, that extra manager reference is also released
Assert.AreEqual(2u, transformMapper2.Get()->Release());
}
[D2DInputCount(0)]
private partial struct DummyShader : ID2D1PixelShader
{
public float4 Execute()
{
return default;
}
}
[TestMethod]
public unsafe void UpdateConstantBufferFromTransformMapper()
{
using ComPtr<ID2D1Factory2> d2D1Factory2 = D2D1Helper.CreateD2D1Factory2();
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1<ShaderWithDispatchArea>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<ShaderWithDispatchArea>(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf());
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new ShaderWithDispatchArea(111, 222), d2D1Effect.Get());
DispatchAreaTransformMapper transformMapper = new() { ExpectedWidth = 111, ExpectedHeight = 222 };
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
string sourcePath = Path.Combine(assemblyPath, "Assets", "Landscape.png");
string expectedPath = Path.Combine(assemblyPath, "Assets", "RadialFadeOut.png");
ReadOnlyMemory<byte> pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height);
using ComPtr<ID2D1Bitmap> d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, d2D1Effect.Get());
using ComPtr<ID2D1Bitmap> d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height);
D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get());
using ComPtr<ID2D1Bitmap1> d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect);
string destinationPath = Path.Combine(assemblyPath, "temp", $"{nameof(UpdateConstantBufferFromTransformMapper)}.png");
_ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits);
TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f);
}
private sealed class DispatchAreaTransformMapper : D2D1TransformMapper<ShaderWithDispatchArea>
{
public int ExpectedWidth;
public int ExpectedHeight;
public override void MapInputsToOutput(
D2D1DrawInfoUpdateContext<ShaderWithDispatchArea> drawInfoUpdateContext,
ReadOnlySpan<Rectangle> inputs,
ReadOnlySpan<Rectangle> opaqueInputs,
out Rectangle output,
out Rectangle opaqueOutput)
{
ShaderWithDispatchArea shader = drawInfoUpdateContext.GetConstantBuffer();
Assert.AreEqual(shader.Width, this.ExpectedWidth);
Assert.AreEqual(shader.Height, this.ExpectedHeight);
shader.Width = inputs[0].Width;
shader.Height = inputs[0].Height;
drawInfoUpdateContext.SetConstantBuffer(in shader);
output = inputs[0];
opaqueOutput = Rectangle.Empty;
}
public override void MapInvalidOutput(int inputIndex, in Rectangle invalidInput, out Rectangle invalidOutput)
{
invalidOutput = invalidInput;
}
public override void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs)
{
inputs.Fill(output);
}
}
[D2DInputCount(1)]
[D2DInputSimple(0)]
[D2DRequiresScenePosition]
[AutoConstructor]
private partial struct ShaderWithDispatchArea : ID2D1PixelShader
{
public int Width;
public int Height;
public float4 Execute()
{
// Get the current integer coordinate and input color
int2 xy = (int2)D2D.GetScenePosition().XY;
float4 color = D2D.GetInput(0);
// Calculate the center and size of the largest circle centered in the image
float2 center = new((uint)this.Width / 2, (uint)this.Height / 2);
int diameter = Hlsl.Min(this.Width, this.Height);
int radius = (int)((uint)diameter / 2);
// Calculate the distance from the center, to adjust the fade out
float distance = Hlsl.Distance(xy, center);
float falloff = radius / 2u;
float alpha = 0;
// If the pixel is close enough, keep it fully visible
if (distance <= falloff)
{
alpha = 1;
}
else if (distance <= radius)
{
// Otherwise, linearly fade it out until the outer radius is reached
float delta = radius - distance;
alpha = delta / falloff;
}
return new(color.RGB, alpha);
}
}
}
+10 -6
ファイルの表示
@@ -317,8 +317,8 @@ public sealed partial class BokehBlurEffect
d2D1DeviceContext.Get()->SetRenderingControls(&d2D1RenderingControls);
// Register all necessary effects
D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), VerticalConvolution.Transform, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), HorizontalConvolutionAndAccumulatePartials.Transform, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<VerticalConvolution.Shader>(d2D1Factory2.Get(), out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<HorizontalConvolutionAndAccumulatePartials.Shader>(d2D1Factory2.Get(), out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<GammaHighlight>(d2D1Factory2.Get(), out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<InverseGammaHighlight>(d2D1Factory2.Get(), out _);
@@ -344,6 +344,10 @@ public sealed partial class BokehBlurEffect
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<VerticalConvolution.Shader>(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectsForReals[i].GetAddressOf());
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<VerticalConvolution.Shader>(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectsForImaginaries[i].GetAddressOf());
D2D1PixelShaderEffect.CreateFromD2D1DeviceContext<HorizontalConvolutionAndAccumulatePartials.Shader>(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffects[i].GetAddressOf());
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(verticalConvolutionEffectsForReals[i].Get(), VerticalConvolution.Transform);
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(verticalConvolutionEffectsForImaginaries[i].Get(), VerticalConvolution.Transform);
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(horizontalConvolutionEffects[i].Get(), HorizontalConvolutionAndAccumulatePartials.Transform);
}
// Create the border effect to clamp the input image
@@ -494,9 +498,9 @@ public sealed partial class BokehBlurEffect
private sealed partial class VerticalConvolution
{
/// <summary>
/// The <see cref="ID2D1TransformMapperFactory{T}"/> for the shader.
/// The <see cref="D2D1TransformMapper{T}"/> for the shader.
/// </summary>
public static ID2D1TransformMapperFactory<Shader> Transform { get; } = D2D1TransformMapperFactory<Shader>.Inflate(static (in Shader shader) => (0, shader.kernelLength, 0, shader.kernelLength));
public static D2D1TransformMapper<Shader> Transform { get; } = D2D1TransformMapperFactory<Shader>.Inflate(static (in Shader shader) => (0, shader.kernelLength, 0, shader.kernelLength));
/// <summary>
/// Kernel for the vertical convolution pass for real or imaginary components.
@@ -541,9 +545,9 @@ public sealed partial class BokehBlurEffect
private sealed partial class HorizontalConvolutionAndAccumulatePartials
{
/// <summary>
/// The <see cref="ID2D1TransformMapperFactory{T}"/> for the shader.
/// The <see cref="D2D1TransformMapper{T}"/> for the shader.
/// </summary>
public static ID2D1TransformMapperFactory<Shader> Transform { get; } = D2D1TransformMapperFactory<Shader>.Inflate(static (in Shader shader) => (shader.kernelLength, 0, shader.kernelLength, 0));
public static D2D1TransformMapper<Shader> Transform { get; } = D2D1TransformMapperFactory<Shader>.Inflate(static (in Shader shader) => (shader.kernelLength, 0, shader.kernelLength, 0));
/// <summary>
/// Kernel for the horizontal convolution pass.
+19 -9
ファイルの表示
@@ -22,7 +22,7 @@ internal static class D2D1TestRunner
/// Executes a pixel shader and compares the expected results.
/// </summary>
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
/// <param name="transformMapperFactory">A custom <see cref="ID2D1TransformMapper{T}"/> factory for the effect.</param>
/// <param name="transformMapper">A custom <see cref="D2D1TransformMapper{T}"/> instance for the effect.</param>
/// <param name="originalFileName">The name of the source image.</param>
/// <param name="expectedFileName">The name of the expected result image.</param>
/// <param name="destinationFileName">The name of the destination image to save results to.</param>
@@ -30,7 +30,7 @@ internal static class D2D1TestRunner
/// <param name="threshold">The allowed difference threshold for the normalized delta.</param>
public static void RunAndCompareShader<T>(
in T shader,
ID2D1TransformMapperFactory<T>? transformMapperFactory,
D2D1TransformMapper<T>? transformMapper,
string originalFileName,
string expectedFileName,
[CallerMemberName] string destinationFileName = "",
@@ -49,7 +49,7 @@ internal static class D2D1TestRunner
// Run the shader
ExecutePixelShaderAndSaveToFile(
in shader,
transformMapperFactory,
transformMapper,
originalPath,
destinationPath);
@@ -104,12 +104,12 @@ internal static class D2D1TestRunner
/// </summary>
/// <typeparam name="T">The shader type to execute.</typeparam>
/// <param name="shader">The shader to run.</param>
/// <param name="transformMapperFactory">A custom <see cref="ID2D1TransformMapper{T}"/> factory for the effect.</param>
/// <param name="transformMapper">A custom <see cref="D2D1TransformMapper{T}"/> instance for the effect.</param>
/// <param name="sourcePath">The source path for the image to run the shader on.</param>
/// <param name="destinationPath">The destination path for the result.</param>
private static unsafe void ExecutePixelShaderAndSaveToFile<T>(
in T shader,
ID2D1TransformMapperFactory<T>? transformMapperFactory,
D2D1TransformMapper<T>? transformMapper,
string sourcePath,
string destinationPath)
where T : unmanaged, ID2D1PixelShader
@@ -118,7 +118,7 @@ internal static class D2D1TestRunner
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), transformMapperFactory, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<T>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -126,6 +126,11 @@ internal static class D2D1TestRunner
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get());
if (transformMapper is not null)
{
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
}
ReadOnlyMemory<byte> pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height);
using ComPtr<ID2D1Bitmap> d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, d2D1Effect.Get());
@@ -146,12 +151,12 @@ internal static class D2D1TestRunner
/// <param name="shader">The shader to run.</param>
/// <param name="width">The resulting width.</param>
/// <param name="height">The resulting height.</param>
/// <param name="transformMapperFactory">A custom <see cref="ID2D1TransformMapper{T}"/> factory for the effect.</param>
/// <param name="transformMapper">A custom <see cref="D2D1TransformMapper{T}"/> instance for the effect.</param>
/// <param name="destinationPath">The destination path for the result.</param>
/// <param name="resourceTextures">The additional resource textures to use to run the shader.</param>
private static unsafe void ExecutePixelShaderAndSaveToFile<T>(
in T shader,
ID2D1TransformMapperFactory<T>? transformMapperFactory,
D2D1TransformMapper<T>? transformMapper,
int width,
int height,
string destinationPath,
@@ -162,7 +167,7 @@ internal static class D2D1TestRunner
using ComPtr<ID2D1Device> d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get());
using ComPtr<ID2D1DeviceContext> d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get());
D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), transformMapperFactory, out _);
D2D1PixelShaderEffect.RegisterForD2D1Factory1<T>(d2D1Factory2.Get(), out _);
using ComPtr<ID2D1Effect> d2D1Effect = default;
@@ -170,6 +175,11 @@ internal static class D2D1TestRunner
D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get());
if (transformMapper is not null)
{
D2D1PixelShaderEffect.SetTransformMapperForD2D1Effect(d2D1Effect.Get(), transformMapper);
}
foreach ((int index, D2D1ResourceTextureManager resourceTextureManager) in resourceTextures)
{
D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, index);