Add GetPixelShaderEffectRegistrationBlob<T> APIs

このコミットが含まれているのは:
Sergio Pedri committed 2022-04-24 21:04:31 +02:00
1 親 993308f6e0
コミット f6282f53ff
4ファイル変更
+390 -3

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

+1
ファイルの表示
@@ -9,6 +9,7 @@
<Import_RootNamespace>ComputeSharp.D2D1.NetStandard</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)System\Buffers\BitOperations.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics.CodeAnalysis\DoesNotReturnAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Math.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\RuntimeHelpers.cs" />
+32
ファイルの表示
@@ -0,0 +1,32 @@
using System.Runtime.CompilerServices;
namespace ComputeSharp.D2D1.NetStandard.System.Buffers;
/// <summary>
/// A polyfill type that mirrors some methods from <see cref="BitOperations"/> on .NET 6.
/// </summary>
internal static class BitOperations
{
/// <summary>
/// Rounds the given integral value up to a power of 2.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// The smallest power of 2 which is greater than or equal to <paramref name="value"/>.
/// If <paramref name="value"/> is 0 or the result overflows, returns 0.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint RoundUpToPowerOf2(uint value)
{
// Based on https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
--value;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
return value + 1;
}
}
+235
ファイルの表示
@@ -0,0 +1,235 @@
using System;
using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
#if !NET6_0_OR_GREATER
using ComputeSharp.D2D1.NetStandard.System.Text;
using BitOperations = ComputeSharp.D2D1.NetStandard.System.Buffers.BitOperations;
#endif
namespace ComputeSharp.D2D1.Shaders.Interop.Buffers;
/// <summary>
/// Represents a heap-based, array-backed output sink into which binary data can be written.
/// </summary>
internal ref struct ArrayPoolBinaryWriter
{
/// <summary>
/// The default buffer size to use to expand empty arrays.
/// </summary>
public const int DefaultInitialBufferSize = 256;
/// <summary>
/// The underlying <see cref="byte"/> array.
/// </summary>
private byte[]? array;
/// <summary>
/// The starting offset within <see cref="array"/>.
/// </summary>
private int index;
/// <summary>
/// Initializes a new instance of the <see cref="ArrayPoolBinaryWriter"/> class.
/// </summary>
public ArrayPoolBinaryWriter(int capacity)
{
this.array = ArrayPool<byte>.Shared.Rent(capacity);
this.index = 0;
}
/// <summary>
/// Gets the data written to the underlying buffer so far, as a <see cref="ReadOnlySpan{T}"/>.
/// </summary>
public ReadOnlySpan<byte> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
byte[]? array = this.array;
if (array is null)
{
ThrowObjectDisposedException();
}
return array!.AsSpan(0, this.index);
}
}
/// <summary>
/// Writes a value of type <typeparamref name="T"/> into the buffer.
/// </summary>
/// <typeparam name="T">The type of value to write.</typeparam>
/// <param name="value">The value to write.</param>
public unsafe void Write<T>(in T value)
where T : unmanaged
{
Span<byte> span = GetSpan(sizeof(T));
MemoryMarshal.Write(span, ref Unsafe.AsRef(in value));
Advance(sizeof(T));
}
/// <summary>
/// Writes text as UTF8 bytes into the buffer.
/// </summary>
/// <param name="text">The text to write.</param>
public unsafe void WriteAsUtf8(string text)
{
int maximumByteSize = Encoding.UTF8.GetMaxByteCount(text.Length);
Span<byte> span = GetSpan(maximumByteSize);
int writtenBytes = Encoding.UTF8.GetBytes(text.AsSpan(), span);
Advance(writtenBytes);
}
/// <summary>
/// Advances the current writer.
/// </summary>
/// <param name="count">The amount to advance.</param>
/// <remarks>Must be called after <see cref="GetSpan"/>.</remarks>
private void Advance(int count)
{
byte[]? array = this.array;
if (array is null)
{
ThrowObjectDisposedException();
}
if (count < 0)
{
ThrowArgumentOutOfRangeExceptionForNegativeCount();
}
if (this.index > array!.Length - count)
{
ThrowArgumentExceptionForAdvancedTooFar();
}
this.index += count;
}
/// <summary>
/// Gets a <see cref="Span{T}"/> to write data to, with an optional minimum capacity.
/// </summary>
/// <param name="sizeHint">The capacity to request.</param>
/// <returns>A <see cref="Span{T}"/> to write data to.</returns>
private Span<byte> GetSpan(int sizeHint = 0)
{
CheckBufferAndEnsureCapacity(sizeHint);
return this.array.AsSpan(this.index);
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBufferAndEnsureCapacity(int sizeHint)
{
byte[]? array = this.array;
if (array is null)
{
ThrowObjectDisposedException();
}
if (sizeHint < 0)
{
ThrowArgumentOutOfRangeExceptionForNegativeSizeHint();
}
if (sizeHint == 0)
{
sizeHint = 1;
}
if (sizeHint > array!.Length - this.index)
{
ResizeBuffer(sizeHint);
}
}
/// <summary>
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void ResizeBuffer(int sizeHint)
{
uint minimumSize = (uint)this.index + (uint)sizeHint;
// The ArrayPool<T> class has a maximum threshold of 1024 * 1024 for the maximum length of
// pooled arrays, and once this is exceeded it will just allocate a new array every time
// of exactly the requested size. In that case, we manually round up the requested size to
// the nearest power of two, to ensure that repeated consecutive writes when the array in
// use is bigger than that threshold don't end up causing a resize every single time.
if (minimumSize > 1024 * 1024)
{
minimumSize = BitOperations.RoundUpToPowerOf2(minimumSize);
}
byte[] newArray = ArrayPool<byte>.Shared.Rent((int)minimumSize);
Buffer.BlockCopy(this.array!, 0, newArray, 0, this.index);
ArrayPool<byte>.Shared.Return(this.array!);
this.array = newArray;
}
/// <inheritdoc/>
public void Dispose()
{
byte[]? array = this.array;
if (array is null)
{
return;
}
this.array = null;
ArrayPool<byte>.Shared.Return(array);
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> when the requested count is negative.
/// </summary>
private static void ThrowArgumentOutOfRangeExceptionForNegativeCount()
{
throw new ArgumentOutOfRangeException("count", "The count can't be a negative value.");
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> when the size hint is negative.
/// </summary>
private static void ThrowArgumentOutOfRangeExceptionForNegativeSizeHint()
{
throw new ArgumentOutOfRangeException("sizeHint", "The size hint can't be a negative value.");
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> when the requested count is negative.
/// </summary>
private static void ThrowArgumentExceptionForAdvancedTooFar()
{
throw new ArgumentException("The buffer writer has advanced too far.");
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> when <see cref="array"/> is <see langword="null"/>.
/// </summary>
private static void ThrowObjectDisposedException()
{
throw new ObjectDisposedException("The current buffer has already been disposed.");
}
}
+122 -3
ファイルの表示
@@ -7,6 +7,7 @@ using System.Text;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Interop.Effects;
using ComputeSharp.D2D1.Shaders.Dispatching;
using ComputeSharp.D2D1.Shaders.Interop.Buffers;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
@@ -65,15 +66,14 @@ unsafe partial class D2D1InteropServices
for (int i = 0; i < PixelShaderEffect.For<T>.NumberOfInputs; i++)
{
effectInputsBuilder.Append($"<Input name='Source");
effectInputsBuilder.Append("<Input name='Source");
effectInputsBuilder.Append(i);
effectInputsBuilder.Append($"'/>");
effectInputsBuilder.Append("'/>");
}
// Prepare the XML with a variable number of inputs
string xml = @$"<?xml version='1.0'?>
<Effect>
<!-- System Properties -->
<Property name='DisplayName' type='string' value='{typeof(T).FullName}'/>
<Property name='Author' type='string' value='ComputeSharp.D2D1'/>
<Property name='Category' type='string' value='Stylize'/>
@@ -121,6 +121,125 @@ unsafe partial class D2D1InteropServices
}
}
/// <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>
/// <remarks>For more info and for details on the binary format, see <see cref="GetPixelShaderEffectRegistrationBlob{T}(Func{ID2D1TransformMapper{T}}?, out Guid)"/>.</remarks>
public static unsafe ReadOnlyMemory<byte> GetPixelShaderEffectRegistrationBlob<T>(out Guid effectId)
where T : unmanaged, ID2D1PixelShader
{
return GetPixelShaderEffectRegistrationBlob<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>
/// <remarks>For more info and for details on the binary format, see <see cref="GetPixelShaderEffectRegistrationBlob{T}(Func{ID2D1TransformMapper{T}}?, out Guid)"/>.</remarks>
public static unsafe ReadOnlyMemory<byte> GetPixelShaderEffectRegistrationBlob<T, TMapper>(out Guid effectId)
where T : unmanaged, ID2D1PixelShader
where TMapper : class, ID2D1TransformMapper<T>, new()
{
return GetPixelShaderEffectRegistrationBlob(static () => new TMapper(), 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>
/// <remarks>
/// <para>
/// The binary blob contains information with the following format:
/// <list type="bullet">
/// <item>The effect id (a <see cref="Guid"/>).</item>
/// <item>The number of inputs for the effect (an <see cref="int"/>).</item>
/// <item>The effect XML description (as null-terminated UTF8 text).</item>
/// <item>The number of property bindings (an <see cref="int"/>).</item>
/// <item>The property name (as null-terminated UTF8 text).</item>
/// <item>The property getter (a <see langword="delegate* unmanaged[Stdcall]&lt;IUnknown*, byte*, uint, uint*, HRESULT&gt;"/>).</item>
/// <item>The property setter (a <see langword="delegate* unmanaged[Stdcall]&lt;IUnknown*, byte*, uint, HRESULT&gt;"/>).</item>
/// <item>The effect factory (a <see langword="delegate* unmanaged[Stdcall]&lt;IUnknown**, byte*, uint, HRESULT&gt;"/>).</item>
/// </list>
/// The property name, getter and setter are grouped together after the number of bindings.
/// </para>
/// <para>
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.
/// </para>
/// </remarks>
public static unsafe ReadOnlyMemory<byte> GetPixelShaderEffectRegistrationBlob<T>(Func<ID2D1TransformMapper<T>>? mapperFactory, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
{
effectId = default;
PixelShaderEffect.For<T>.Initialize(mapperFactory);
using ArrayPoolBinaryWriter writer = new(ArrayPoolBinaryWriter.DefaultInitialBufferSize);
// Effect id and number of inputs
writer.Write(*PixelShaderEffect.For<T>.Id);
writer.Write(PixelShaderEffect.For<T>.NumberOfInputs);
// Build the XML text
writer.WriteAsUtf8(@"<?xml version='1.0'?>
<Effect>
<Property name='DisplayName' type='string' value='");
writer.WriteAsUtf8(typeof(T).FullName!);
writer.WriteAsUtf8(@"'/>
<Property name='Author' type='string' value='ComputeSharp.D2D1'/>
<Property name='Category' type='string' value='Stylize'/>
<Property name='Description' type='string' value='A custom D2D1 effect using a pixel shader'/>
<Inputs>
");
// Add the input nodes
for (int i = 0; i < PixelShaderEffect.For<T>.NumberOfInputs; i++)
{
writer.WriteAsUtf8("<Input name='Source");
writer.WriteAsUtf8(i.ToString());
writer.WriteAsUtf8($"'/>");
}
// Write the last part of the XML (including the buffer property)
writer.WriteAsUtf8(@"
</Inputs>
<Property name='Buffer' type='blob'>
<Property name='DisplayName' type='string' value='Buffer'/>
</Property>
</Effect>");
// Null terminator for the text
writer.Write((byte)'\0');
// Property accessors
#if NET6_0_OR_GREATER
nint getBufferPointer = (nint)(delegate* unmanaged<IUnknown*, byte*, uint, uint*, int>)&PixelShaderEffect.GetConstantBuffer;
nint setBufferPointer = (nint)(delegate* unmanaged<IUnknown*, byte*, uint, int>)&PixelShaderEffect.SetConstantBuffer;
#else
nint getBufferPointer = Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.GetConstantBufferWrapper);
nint setBufferPointer = Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.SetConstantBufferWrapper);
#endif
// Bindings
writer.Write(1);
writer.WriteAsUtf8("Buffer");
writer.Write((byte)'\0');
writer.Write(getBufferPointer);
writer.Write(setBufferPointer);
// Effect factory
writer.Write((nint)PixelShaderEffect.For<T>.Factory);
effectId = *PixelShaderEffect.For<T>.Id;
return writer.WrittenSpan.ToArray();
}
/// <summary>
/// Creates an effect wrapping an input D2D1 pixel shader, by calling <c>ID2D1DeviceContext::CreateEffect</c>.
/// </summary>