Add ID2D1Shader.InitializeFromDispatchData API to support transforms

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

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

@@ -0,0 +1,127 @@
using System.Collections.Immutable;
using ComputeSharp.D2D1.__Internals;
using ComputeSharp.D2D1.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <inheritdoc/>
partial class InitializeFromDispatchData
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>InitializeFromDispatchData</c> method.
/// </summary>
/// <param name="dispatchInfo">The dispatch info gathered for the current shader.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>InitializeFromDispatchData</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(DispatchDataInfo dispatchInfo)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InitializeFromDispatchData(global::System.ReadOnlySpan<byte> data)
// {
// <BODY>
// }
return
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier("InitializeFromDispatchData"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}")))
.AddParameterListParameters(Parameter(Identifier("data")).WithType(
GenericName(Identifier("global::System.ReadOnlySpan"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))))
.WithBody(Block(GetDispatchDataUnloadingStatements(dispatchInfo.FieldInfos)));
}
/// <summary>
/// Gets a sequence of statements to initialize a shader from a serialized dispatch data buffer.
/// </summary>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to initialize a shader from the serialized dispatch data buffer.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataUnloadingStatements(ImmutableArray<FieldInfo> fieldInfos)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
// Insert the fallback for empty shaders. This will generate the following code:
//
// if (data.IsEmpty)
// {
// return;
// }
statements.Add(
IfStatement(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("data"),
IdentifierName("IsEmpty")),
Block(ReturnStatement())));
// ref byte r0 = ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(data);
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::System.Runtime.InteropServices.MemoryMarshal"),
IdentifierName("GetReference")))
.AddArgumentListArguments(Argument(IdentifierName("data")))))))));
// Generate loading statements for each captured field
foreach (FieldInfo fieldInfo in fieldInfos)
{
switch (fieldInfo)
{
case FieldInfo.Primitive primitive:
// Read a primitive value from the target buffer. This will generate:
//
// Unsafe.AsRef(in <FIELD_PATH>) = global::System.Runtime.CompilerServices.Unsafe.As<byte, global::<TYPE_NAME>>(
// ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>))
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", primitive.FieldPath)})"),
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, global::{primitive.TypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"))));
break;
case FieldInfo.NonLinearMatrix matrix:
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
// Declare a local to index into individual rows. This will generate:
//
// ref <ROW_TYPE> <ROW_NAME> = ref global::System.Runtime.CompilerServices.Unsafe.As<global::<TYPE_NAME>, <ROW_TYPE_NAME>>(
// ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in <FIELD_PATH>));
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
//
// ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
// global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0) = global::System.Runtime.CompilerServices.Unsafe.As<byte, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset));
// global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1) = global::System.Runtime.CompilerServices.Unsafe.As<byte, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16)));
for (int j = 0; j < matrix.Rows; j++)
{
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"),
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"))));
}
break;
}
}
return statements.ToImmutable();
}
}
}
@@ -79,7 +79,7 @@ partial class ID2D1ShaderGenerator
// This will result in the following (assuming Float2x3 m):
//
// ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < matrix.Rows; j++)
{
@@ -93,14 +93,14 @@ partial class ID2D1ShaderGenerator
}
}
// global::System.Span<uint> span0 = stackalloc uint[<VARIABLES>];
// global::System.Span<uint> data = stackalloc uint[<VARIABLES>];
statements.Insert(0,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
VariableDeclarator(Identifier("data"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
@@ -108,7 +108,7 @@ partial class ID2D1ShaderGenerator
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
// ref uint r0 = ref span0[0];
// ref uint r0 = ref data[0];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
@@ -116,13 +116,13 @@ partial class ID2D1ShaderGenerator
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
ElementAccessExpression(IdentifierName("data"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadConstantBuffer(span0);
// loader.LoadConstantBuffer(data);
statements.Add(
ExpressionStatement(
InvocationExpression(
@@ -130,7 +130,7 @@ partial class ID2D1ShaderGenerator
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadConstantBuffer")))
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
.AddArgumentListArguments(Argument(IdentifierName("data")))));
return statements.ToImmutable();
}
+9
ファイルの表示
@@ -119,6 +119,15 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}", compilationUnit.ToFullString());
});
// Generate the InitializeFromDispatchData() methods
context.RegisterSourceOutput(dispatchDataInfo, static (context, item) =>
{
MethodDeclarationSyntax loadDispatchDataMethod = InitializeFromDispatchData.GetSyntax(item.Dispatch);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, false);
context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(InitializeFromDispatchData)}", compilationUnit.ToFullString());
});
// Get the filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string HlslSource)> hlslSourceInfo =
shaderInfo
@@ -6,11 +6,44 @@ namespace ComputeSharp.D2D1;
/// <summary>
/// An <see langword="interface"/> providing support for custom, stateful draw transform mappings for shaders.
/// </summary>
public interface ID2D1DrawTransformMapper
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="shader">The input D2D1 pixel shader being executed on the current effect (this can be used to retrieve shader properties).</param>
/// <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>
@@ -23,31 +56,12 @@ public interface ID2D1DrawTransformMapper
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapoutputrecttoinputrects"/>.
/// </para>
/// </remarks>
void MapOutputToInputs(in Rectangle output, Span<Rectangle> inputs);
/// <summary>
/// Performs the inverse mapping of <see cref="MapOutputToInputs(in Rectangle, Span{Rectangle})"/>.
/// </summary>
/// <param name="inputs">The input rectangles to be mapped to the output rectangle. This parameter is always equal to the input bounds.</param>
/// <param name="opaqueInputs">The input rectangles to be mapped to the opaque output rectangle.</param>
/// <param name="output">The output rectangle that maps to the corresponding input rectangle.</param>
/// <param name="opaqueOutput">The output rectangle that maps to the corresponding opaque input rectangle.</param>
/// <remarks>
/// <para>
/// Unlike <see cref="MapOutputToInputs(in Rectangle, Span{Rectangle})"/> and <see cref="MapInvalidOutput(int, Rectangle, out Rectangle)"/>, this
/// method is explicitly called by the renderer at a determined place in its rendering algorithm. The transform implementation may change its state
/// based on the input rectangles and use this information to control its rendering information. This method is always called before the
/// <see cref="MapInvalidOutput(int, Rectangle, out Rectangle)"/> and <see cref="MapOutputToInputs(in Rectangle, Span{Rectangle})"/> methods.
/// </para>
/// <para>
/// For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1effectauthor/nf-d2d1effectauthor-id2d1transform-mapinputrectstooutputrect"/>.
/// </para>
/// </remarks>
void MapInputsToOutput(ReadOnlySpan<Rectangle> inputs, ReadOnlySpan<Rectangle> opaqueInputs, out Rectangle output, out Rectangle opaqueOutput);
void MapOutputToInputs(in T shader, in Rectangle output, Span<Rectangle> inputs);
/// <summary>
/// Sets the input rectangles for this rendering pass into the transform.
/// </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="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>
@@ -55,12 +69,12 @@ public interface ID2D1DrawTransformMapper
/// <para>
/// The transform implementation must regard this method as purely functional. The transform implementation can base the mapped input rectangle on
/// the transform implementation's current state as specified by the encapsulating effect properties. But the transform implementation can't change
/// its own state in response to a call to <see cref="MapInvalidOutput(int, Rectangle, out Rectangle)"/>. Direct2D can call this method at any time
/// and in any sequence following a call to <see cref="MapInputsToOutput(ReadOnlySpan{Rectangle}, ReadOnlySpan{Rectangle}, out Rectangle, out Rectangle)"/>.
/// 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);
void MapInvalidOutput(in T shader, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput);
}
+16
ファイルの表示
@@ -10,6 +10,22 @@ namespace ComputeSharp.D2D1.__Internals;
[Obsolete("This interface is not intended to be used directly by user code")]
public interface ID2D1Shader
{
/// <summary>
/// Initializes the current shader from a buffer with the serialized dispatch data.
/// </summary>
/// <param name="data">The input buffer with the serialized dispatch data.</param>
/// <remarks>The input buffer must be retrieved from <see cref="LoadDispatchData"/>.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void InitializeFromDispatchData(ReadOnlySpan<byte> data)
#if NET6_0_OR_GREATER
{
throw new NotImplementedException();
}
#else
;
#endif
/// <summary>
/// Loads the dispatch data for the shader.
/// </summary>
+4 -4
ファイルの表示
@@ -34,13 +34,13 @@ unsafe partial class D2D1InteropServices
/// Registers an effect from an input D2D1 pixel shader, by calling <c>ID2D1Factory1::RegisterEffectFromString</c>.
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to register.</typeparam>
/// <typeparam name="TMapper">The type of <see cref="ID2D1DrawTransformMapper"/> implementation to register.</typeparam>
/// <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>
/// <remarks>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</remarks>
public static unsafe void RegisterPixelShaderEffectForD2D1Factory1<T, TMapper>(void* d2D1Factory1, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
where TMapper : class, ID2D1DrawTransformMapper, new()
where TMapper : class, ID2D1TransformMapper<T>, new()
{
RegisterPixelShaderEffectForD2D1Factory1<T>(d2D1Factory1, static () => new TMapper(), out effectId);
}
@@ -50,10 +50,10 @@ unsafe partial class D2D1InteropServices
/// </summary>
/// <typeparam name="T">The type of D2D1 pixel shader to register.</typeparam>
/// <param name="d2D1Factory1">A pointer to the <c>ID2D1Factory1</c> instance to use.</param>
/// <param name="mapperFactory">An optional factory of <see cref="ID2D1DrawTransformMapper"/> instances to use for the transform.</param>
/// <param name="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>For more info, see <see href="https://docs.microsoft.com/windows/win32/api/d2d1_1/nf-d2d1_1-id2d1factory1-registereffectfromstring"/>.</remarks>
public static unsafe void RegisterPixelShaderEffectForD2D1Factory1<T>(void* d2D1Factory1, Func<ID2D1DrawTransformMapper>? mapperFactory, out Guid effectId)
public static unsafe void RegisterPixelShaderEffectForD2D1Factory1<T>(void* d2D1Factory1, Func<ID2D1TransformMapper<T>>? mapperFactory, out Guid effectId)
where T : unmanaged, ID2D1PixelShader
{
effectId = default;
+106
ファイルの表示
@@ -0,0 +1,106 @@
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="buffer">The buffer with the serialized shader dispatch data, if any.</param>
/// <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(ReadOnlySpan<byte> buffer, in Rectangle output, Span<Rectangle> inputs);
/// <inheritdoc cref="ID2D1TransformMapper{T}.MapInvalidOutput"/>
/// <param name="buffer">The buffer with the serialized shader dispatch data, if any.</param>
/// <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(ReadOnlySpan<byte> buffer, 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 For<T>? Get(ID2D1TransformMapper<T>? transformMapper)
{
if (transformMapper is null)
{
return null;
}
return new(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(ReadOnlySpan<byte> buffer, in Rectangle output, Span<Rectangle> inputs)
{
Unsafe.SkipInit(out T shader);
shader.InitializeFromDispatchData(buffer);
this.transformMapper.MapOutputToInputs(in shader, in output, inputs);
}
/// <inheritdoc/>
public override void MapInvalidOutput(ReadOnlySpan<byte> buffer, int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput)
{
Unsafe.SkipInit(out T shader);
shader.InitializeFromDispatchData(buffer);
this.transformMapper.MapInvalidOutput(in shader, inputIndex, invalidInput, out invalidOutput);
}
}
}
@@ -127,7 +127,7 @@ partial struct PixelShaderEffect
return E.E_INVALIDARG;
}
if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper)
if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper)
{
Rectangle output = outputRect->ToRectangle();
Span<Rectangle> inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectsCount);
@@ -137,10 +137,12 @@ partial struct PixelShaderEffect
inputs[i] = inputRects[i].ToRectangle();
}
ReadOnlySpan<byte> buffer = new(@this->constantBuffer, @this->constantBufferSize);
// Invoke MapOutputToInputs and handle exceptions so they don't cross the ABI boundary
try
{
d2D1DrawTransformMapper.MapOutputToInputs(in output, inputs);
d2D1TransformMapper.MapOutputToInputs(buffer, in output, inputs);
}
catch (Exception e)
{
@@ -175,7 +177,7 @@ partial struct PixelShaderEffect
return E.E_INVALIDARG;
}
if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper)
if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper)
{
Span<Rectangle> inputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
Span<Rectangle> opaqueInputs = stackalloc Rectangle[8].Slice(0, (int)inputRectCount);
@@ -186,13 +188,15 @@ partial struct PixelShaderEffect
opaqueInputs[i] = inputOpaqueSubRects[i].ToRectangle();
}
ReadOnlySpan<byte> buffer = new(@this->constantBuffer, @this->constantBufferSize);
Rectangle output;
Rectangle opaqueOutput;
// Handle exceptions, as mentioned above
try
{
d2D1DrawTransformMapper.MapInputsToOutput(inputs, opaqueInputs, out output, out opaqueOutput);
d2D1TransformMapper.MapInputsToOutput(buffer, inputs, opaqueInputs, out output, out opaqueOutput);
}
catch (Exception e)
{
@@ -230,15 +234,17 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
if (@this->d2D1DrawTransformMapperFactoryHandle.Target is ID2D1DrawTransformMapper d2D1DrawTransformMapper)
if (@this->d2D1TransformMapperHandle.Target is D2D1TransformMapper d2D1TransformMapper)
{
Rectangle invalidInput = invalidInputRect.ToRectangle();
Rectangle invalidOutput;
ReadOnlySpan<byte> buffer = new(@this->constantBuffer, @this->constantBufferSize);
// Handle exceptions once again
try
{
d2D1DrawTransformMapper.MapInvalidOutput((int)inputIndex, invalidInput, out invalidOutput);
d2D1TransformMapper.MapInvalidOutput(buffer, (int)inputIndex, invalidInput, out invalidOutput);
}
catch (Exception e)
{
+18 -12
ファイルの表示
@@ -97,16 +97,16 @@ internal unsafe partial struct PixelShaderEffect
private static int bytecodeSize;
/// <summary>
/// The factory of <see cref="ID2D1DrawTransformMapper"/> instances to use for each created effect.
/// The factory of <see cref="ID2D1TransformMapper{T}"/> instances to use for each created effect.
/// </summary>
private static Func<ID2D1DrawTransformMapper>? d2D1DrawTransformMapperFactory;
private static Func<ID2D1TransformMapper<T>>? d2D1DrawTransformMapperFactory;
/// <summary>
/// Initializes the <see cref="For{T}"/> shared state.
/// </summary>
/// <param name="factory">The factory of <see cref="ID2D1DrawTransformMapper"/> instances to use for each created effect.</param>
/// <param name="factory">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(Func<ID2D1DrawTransformMapper>? factory)
public static void Initialize(Func<ID2D1TransformMapper<T>>? factory)
{
// This conceptually acts as a static constructor, and this type is
// internal, so in this very specific case locking on the type is fine.
@@ -161,9 +161,15 @@ internal unsafe partial struct PixelShaderEffect
/// <inheritdoc cref="FactoryDelegate"/>
private static int CreateEffect(IUnknown** effectImpl)
{
ID2D1DrawTransformMapper? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Invoke();
ID2D1TransformMapper<T>? d2D1DrawTransformMapper = d2D1DrawTransformMapperFactory?.Invoke();
return PixelShaderEffect.Factory(shaderId, numberOfInputs, bytecode, bytecodeSize, d2D1DrawTransformMapper, effectImpl);
return PixelShaderEffect.Factory(
shaderId,
numberOfInputs,
bytecode,
bytecodeSize,
D2D1TransformMapper.For<T>.Get(d2D1DrawTransformMapper),
effectImpl);
}
}
@@ -272,9 +278,9 @@ internal unsafe partial struct PixelShaderEffect
private int bytecodeSize;
/// <summary>
/// The handle for the <see cref="ID2D1DrawTransformMapper"/> instance in use, if any.
/// The handle for the <see cref="D2D1TransformMapper"/> instance in use, if any.
/// </summary>
private GCHandle d2D1DrawTransformMapperFactoryHandle;
private GCHandle d2D1TransformMapperHandle;
/// <summary>
/// The current input rectangle.
@@ -293,7 +299,7 @@ internal unsafe partial struct PixelShaderEffect
/// <param name="numberOfInputs">The number of inputs for the shader.</param>
/// <param name="bytecode">The shader bytecode.</param>
/// <param name="bytecodeSize">The size of <paramref name="bytecode"/>.</param>
/// <param name="d2D1DrawTransformMapper">The <see cref="ID2D1DrawTransformMapper"/> instance to use for the effect.</param>
/// <param name="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(
@@ -301,7 +307,7 @@ internal unsafe partial struct PixelShaderEffect
int numberOfInputs,
byte* bytecode,
int bytecodeSize,
ID2D1DrawTransformMapper? d2D1DrawTransformMapper,
D2D1TransformMapper? d2D1TransformMapper,
IUnknown** effectImpl)
{
PixelShaderEffect* @this = (PixelShaderEffect*)NativeMemory.Alloc((nuint)sizeof(PixelShaderEffect));
@@ -315,7 +321,7 @@ internal unsafe partial struct PixelShaderEffect
@this->numberOfInputs = numberOfInputs;
@this->bytecode = bytecode;
@this->bytecodeSize = bytecodeSize;
@this->d2D1DrawTransformMapperFactoryHandle = GCHandle.Alloc(d2D1DrawTransformMapper);
@this->d2D1TransformMapperHandle = GCHandle.Alloc(d2D1TransformMapper);
*effectImpl = (IUnknown*)@this;
@@ -419,7 +425,7 @@ internal unsafe partial struct PixelShaderEffect
NativeMemory.Free(this.constantBuffer);
}
this.d2D1DrawTransformMapperFactoryHandle.Free();
this.d2D1TransformMapperHandle.Free();
NativeMemory.Free(Unsafe.AsPointer(ref this));
}
@@ -148,7 +148,7 @@ partial class IShaderGenerator
// This will result in the following (assuming Float2x3 m):
//
// ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) =, global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < matrix.Rows; j++)
{