Merge pull request #592 from Sergio0694/dev/refactor-pse-shared-state

Refactor global state for built-in pixel shader effects
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-10-08 17:59:05 +02:00
コミット 392cf5c0a5
18ファイル変更
+723 -974

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

+32
ファイルの表示
@@ -69,6 +69,22 @@ internal static class ArgumentOutOfRangeExceptionExtensions
}
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> if <paramref name="value"/> is greater than or equal to <paramref name="other"/>.
/// </summary>
/// <param name="_">Dummy value to invoke the extension upon (always pass <see langword="null"/>.</param>
/// <param name="value">The argument to validate as less or equal than <paramref name="other"/>.</param>
/// <param name="other">The value to compare with <paramref name="value"/>.</param>
/// <param name="parameterName">The name of the parameter with which <paramref name="value"/> corresponds.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ThrowIfGreaterThanOrEqual(this ArgumentOutOfRangeException? _, int value, int other, [CallerArgumentExpression(nameof(value))] string? parameterName = null)
{
if (value >= other)
{
Throw(parameterName, value);
}
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> if <paramref name="value"/> is less than <paramref name="other"/>.
/// </summary>
@@ -118,6 +134,22 @@ internal static class ArgumentOutOfRangeExceptionExtensions
}
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> if <paramref name="value"/> is not equal to a given other value.
/// </summary>
/// <param name="_">Dummy value to invoke the extension upon (always pass <see langword="null"/>.</param>
/// <param name="value">The argument to validate.</param>
/// <param name="other">The value to compare against.</param>
/// <param name="parameterName">The name of the parameter with which <paramref name="value"/> corresponds.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ThrowIfNotEqual(this ArgumentOutOfRangeException? _, int value, int other, [CallerArgumentExpression(nameof(value))] string? parameterName = null)
{
if (value != other)
{
Throw(parameterName, value);
}
}
/// <summary>
/// Throws an <see cref="ArgumentOutOfRangeException"/> if <paramref name="value"/> is not in the specified range.
/// </summary>
+2 -2
ファイルの表示
@@ -2,7 +2,7 @@ using System;
using System.Runtime.CompilerServices;
using ABI.Microsoft.Graphics.Canvas;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Interop.Effects;
using ComputeSharp.D2D1.Interop;
#if WINDOWS_UWP
using ComputeSharp.D2D1.Uwp.Extensions;
using ComputeSharp.D2D1.Uwp.Helpers;
@@ -74,7 +74,7 @@ unsafe partial class PixelShaderEffect<T>
if (!this.isEffectFactoryRegistered)
{
ResourceManager.RegisterEffectFactory(
effectId: PixelShaderEffect.For<T>.Instance.Id,
effectId: D2D1PixelShaderEffect.GetEffectId<T>(),
factory: new EffectFactory());
this.isEffectFactoryRegistered = true;
+1 -2
ファイルの表示
@@ -4,7 +4,6 @@ using System.Threading;
using ABI.Microsoft.Graphics.Canvas;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Interop;
using ComputeSharp.D2D1.Interop.Effects;
#if WINDOWS_UWP
using ComputeSharp.D2D1.Uwp.Extensions;
using ComputeSharp.D2D1.Uwp.Helpers;
@@ -262,7 +261,7 @@ unsafe partial class PixelShaderEffect<T>
{
fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect)
{
Guid effectId = PixelShaderEffect.For<T>.Instance.Id;
Guid effectId = D2D1PixelShaderEffect.GetEffectId<T>();
using ComPtr<ID2D1DeviceContext> d2D1DeviceContextEffective = default;
using ComPtr<ID2D1DeviceContextLease> d2D1DeviceContextLease = default;
+8 -8
ファイルの表示
@@ -188,7 +188,7 @@ public static unsafe class D2D1PixelShaderEffect
d2D1PropertyBinding[D2D1PixelShaderEffectProperty.ResourceTextureManager14].setFunction = PixelShaderEffect.SetResourceTextureManager14;
d2D1PropertyBinding[D2D1PixelShaderEffectProperty.ResourceTextureManager15].setFunction = PixelShaderEffect.SetResourceTextureManager15;
fixed (Guid* pGuid = &PixelShaderEffect.For<T>.Instance.Id)
fixed (Guid* pGuid = &GetEffectId<T>())
{
// Register the effect
((ID2D1Factory1*)d2D1Factory1)->RegisterEffectFromString(
@@ -196,10 +196,10 @@ public static unsafe class D2D1PixelShaderEffect
propertyXml: (ushort*)pXml,
bindings: d2D1PropertyBinding,
bindingsCount: (uint)(D2D1PixelShaderEffectProperty.NumberOfAlwaysAvailableProperties + D2D1PixelShader.GetResourceTextureCount<T>()),
effectFactory: PixelShaderEffect.For<T>.Instance.Factory).Assert();
effectFactory: PixelShaderEffect.Globals<T>.Instance.Factory).Assert();
}
effectId = PixelShaderEffect.For<T>.Instance.Id;
effectId = GetEffectId<T>();
}
}
@@ -250,8 +250,8 @@ public static unsafe class D2D1PixelShaderEffect
writer.Write(D2D1EffectRegistrationData.V1.BlobId);
// Effect id and number of inputs
writer.Write(PixelShaderEffect.For<T>.Instance.Id);
writer.Write(PixelShaderEffect.For<T>.Instance.InputCount);
writer.Write(GetEffectId<T>());
writer.Write(D2D1PixelShader.GetInputCount<T>());
// Retrieve the effect XML and include it into the registration blob
using (D2D1EffectXmlFactory.EffectXml effectXml = D2D1EffectXmlFactory.GetXmlBuffer<T>())
@@ -388,14 +388,14 @@ public static unsafe class D2D1PixelShaderEffect
}
// Effect factory
writer.Write((nint)PixelShaderEffect.For<T>.Instance.Factory);
writer.Write((nint)PixelShaderEffect.Globals<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>.Instance.Id;
effectId = GetEffectId<T>();
return registrationBlob;
}
@@ -419,7 +419,7 @@ public static unsafe class D2D1PixelShaderEffect
default(ArgumentNullException).ThrowIfNull(d2D1DeviceContext);
default(ArgumentNullException).ThrowIfNull(d2D1Effect);
fixed (Guid* pGuid = &PixelShaderEffect.For<T>.Instance.Id)
fixed (Guid* pGuid = &GetEffectId<T>())
{
((ID2D1DeviceContext*)d2D1DeviceContext)->CreateEffect(
effectId: pGuid,
-273
ファイルの表示
@@ -1,273 +0,0 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Descriptors;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#if !NET6_0_OR_GREATER
using RuntimeHelpers = ComputeSharp.NetStandard.RuntimeHelpers;
#endif
namespace ComputeSharp.D2D1.Interop.Effects;
/// <summary>
/// A simple <see cref="ID2D1EffectImpl"/> and <see cref="ID2D1DrawTransform"/> implementation for a given pixel shader.
/// </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 sealed class For<T>
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
{
/// <summary>
/// The <see cref="FactoryDelegate"/> wrapper for the shader factory.
/// </summary>
private readonly FactoryDelegate effectFactory;
/// <summary>
/// The <see cref="Guid"/> for the shader.
/// </summary>
/// <remarks>
/// This field could have used <see cref="FixedAddressValueTypeAttribute"/> to reduce some verbosity where it is
/// 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 readonly Guid shaderId;
/// <summary>
/// The size of the constant buffer for the shader.
/// </summary>
private readonly int constantBufferSize;
/// <summary>
/// The number of inputs for the shader.
/// </summary>
private readonly int inputCount;
/// <summary>
/// The buffer with the types of inputs for the shader.
/// </summary>
private readonly D2D1PixelShaderInputType* inputTypes;
/// <summary>
/// The number of available input descriptions.
/// </summary>
private readonly int inputDescriptionCount;
/// <summary>
/// The buffer with the available input descriptions for the shader.
/// </summary>
private readonly D2D1InputDescription* inputDescriptions;
/// <summary>
/// The pixel options for the shader.
/// </summary>
private readonly D2D1PixelOptions pixelOptions;
/// <summary>
/// The shader bytecode.
/// </summary>
private readonly byte* bytecode;
/// <summary>
/// The size of <see cref="bytecode"/>.
/// </summary>
private readonly int bytecodeSize;
/// <summary>
/// The buffer precision for the resulting output buffer.
/// </summary>
private readonly D2D1BufferPrecision bufferPrecision;
/// <summary>
/// The channel depth for the resulting output buffer.
/// </summary>
private readonly D2D1ChannelDepth channelDepth;
/// <summary>
/// The number of available resource texture descriptions.
/// </summary>
private readonly int resourceTextureDescriptionCount;
/// <summary>
/// The buffer with the available resource texture descriptions for the shader.
/// </summary>
private readonly D2D1ResourceTextureDescription* resourceTextureDescriptions;
/// <summary>
/// Creates a new <see cref="For{T}"/> instance with the specified parameters.
/// </summary>
/// <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.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 the shared <see cref="For{T}"/> instance.
/// </summary>
public static For<T> Instance { get; } = CreateInstance();
/// <summary>
/// Creates a new <see cref="For{T}"/> instance.
/// </summary>
/// <returns>The initialized <see cref="For{T}"/> instance.</returns>
private static For<T> CreateInstance()
{
// Load all shader properties
Guid shaderId = D2D1PixelShaderEffect.GetEffectId<T>();
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);
D2D1PixelShader.GetInputTypes<T>().Span.CopyTo(new Span<D2D1PixelShaderInputType>(inputTypes, inputCount));
// 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));
// Initialize the shared instance with the computed state
return new(
CreateEffect,
shaderId,
constantBufferSize,
inputCount,
inputTypes,
inputDescriptionCount,
inputDescriptions,
pixelOptions,
bytecode,
bytecodeSize,
bufferPrecision,
channelDepth,
resourceTextureDescriptionCount,
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);
}
}
}
+170
ファイルの表示
@@ -0,0 +1,170 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Descriptors;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.D2D1.Interop.Effects;
/// <summary>
/// A simple <see cref="ID2D1EffectImpl"/> and <see cref="ID2D1DrawTransform"/> implementation for a given pixel shader.
/// </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)]
public delegate int FactoryDelegate(IUnknown** effectImpl);
/// <summary>
/// A base type with global values for pixel shader effects.
/// </summary>
public abstract class Globals
{
/// <summary>
/// Gets the <see cref="FactoryDelegate"/> wrapper for the shader factory.
/// </summary>
private readonly FactoryDelegate effectFactory;
/// <summary>
/// Creates a new <see cref="Globals"/> instance with the specified parameters.
/// </summary>
/// <param name="effectFactory">The <see cref="FactoryDelegate"/> wrapper for the shader factory.</param>
protected Globals(FactoryDelegate effectFactory)
{
this.effectFactory = effectFactory;
}
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.EffectId"/>
public abstract ref readonly Guid EffectId { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.ConstantBufferSize"/>
public abstract int ConstantBufferSize { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.InputCount"/>
public abstract int InputCount { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.ResourceTextureCount"/>
public abstract int ResourceTextureCount { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.InputTypes"/>
public abstract ReadOnlyMemory<D2D1PixelShaderInputType> InputTypes { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.InputDescriptions"/>
public abstract ReadOnlyMemory<D2D1InputDescription> InputDescriptions { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.ResourceTextureDescriptions"/>
public abstract ReadOnlyMemory<D2D1ResourceTextureDescription> ResourceTextureDescriptions { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.PixelOptions"/>
public abstract D2D1PixelOptions PixelOptions { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.BufferPrecision"/>
public abstract D2D1BufferPrecision BufferPrecision { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.ChannelDepth"/>
public abstract D2D1ChannelDepth ChannelDepth { get; }
/// <inheritdoc cref="ID2D1PixelShaderDescriptor{T}.HlslBytecode"/>
public abstract ReadOnlyMemory<byte> HlslBytecode { get; }
/// <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>
/// A generic pixel shader implementation.
/// </summary>
/// <typeparam name="T">The type of shader.</typeparam>
public sealed class Globals<T> : Globals
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
{
/// <summary>
/// The HLSL bytecode (either precompiled, or the currently available one after compilation).
/// </summary>
private ReadOnlyMemory<byte> hlslBytecode;
/// <summary>
/// Creates a new <see cref="Globals"/> instance for shaders of type <typeparamref name="T"/>.
/// </summary>
private Globals()
: base(CreateEffect)
{
}
/// <summary>
/// Gets the shared <see cref="Globals{T}"/> instance to use.
/// </summary>
public static Globals<T> Instance { get; } = new();
/// <inheritdoc/>
public override ref readonly Guid EffectId => ref D2D1PixelShaderEffect.GetEffectId<T>();
/// <inheritdoc/>
public override int ConstantBufferSize => D2D1PixelShader.GetConstantBufferSize<T>();
/// <inheritdoc/>
public override int InputCount => D2D1PixelShader.GetInputCount<T>();
/// <inheritdoc/>
public override int ResourceTextureCount => D2D1PixelShader.GetResourceTextureCount<T>();
/// <inheritdoc/>
public override ReadOnlyMemory<D2D1PixelShaderInputType> InputTypes => D2D1PixelShader.GetInputTypes<T>();
/// <inheritdoc/>
public override ReadOnlyMemory<D2D1InputDescription> InputDescriptions => D2D1PixelShader.GetInputDescriptions<T>();
/// <inheritdoc/>
public override ReadOnlyMemory<D2D1ResourceTextureDescription> ResourceTextureDescriptions => D2D1PixelShader.GetResourceTextureDescriptions<T>();
/// <inheritdoc/>
public override D2D1PixelOptions PixelOptions => D2D1PixelShader.GetPixelOptions<T>();
/// <inheritdoc/>
public override D2D1BufferPrecision BufferPrecision => D2D1PixelShader.GetOutputBufferPrecision<T>();
/// <inheritdoc/>
public override D2D1ChannelDepth ChannelDepth => D2D1PixelShader.GetOutputBufferChannelDepth<T>();
/// <inheritdoc/>
public override ReadOnlyMemory<byte> HlslBytecode
{
get
{
// Fast path if we already have some bytecode (either precompiled, or already compiled)
if (this.hlslBytecode is ReadOnlyMemory<byte> { Length: > 0 } hlslBytecode)
{
return hlslBytecode;
}
// If not, lazily compile the bytecode when requested
return this.hlslBytecode = D2D1PixelShader.LoadBytecode<T>();
}
}
/// <inheritdoc cref="FactoryDelegate"/>
private static int CreateEffect(IUnknown** effectImpl)
{
return PixelShaderEffect.Factory(Instance, effectImpl);
}
}
}
+162 -169
ファイルの表示
@@ -110,7 +110,16 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
return (uint)@this->inputCount;
try
{
return (uint)@this->GetGlobals().InputCount;
}
catch
{
// GetInputCount doesn't respect COM, so it does not return an HRESULT.
// The only thing we can do in this case is just to return 0 instead.
return 0;
}
}
/// <inheritdoc cref="ID2D1DrawTransform.MapOutputRectToInputRects"/>
@@ -119,45 +128,46 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
if (inputRectsCount != @this->inputCount)
try
{
return E.E_INVALIDARG;
}
default(ArgumentOutOfRangeException).ThrowIfNotEqual((int)inputRectsCount, @this->GetGlobals().InputCount, nameof(inputRectsCount));
if (@this->d2D1TransformMapper is not null)
{
// Forward to the current ID2D1TransformMapper instance
HRESULT hresult = @this->d2D1TransformMapper->MapOutputRectToInputRects(outputRect, inputRects, inputRectsCount);
if (!Windows.SUCCEEDED(hresult))
if (@this->d2D1TransformMapper is not null)
{
return hresult;
// Forward to the current ID2D1TransformMapper instance
@this->d2D1TransformMapper->MapOutputRectToInputRects(outputRect, inputRects, inputRectsCount).Assert();
}
}
else
{
// If no custom transform is used, apply the default mapping. In this case, the loop will
// automatically handle cases where no inputs are defined. If inputs are present instead,
// the default mapping will set the input rect for a simple input to be the same as the
// output rect, and the input rect for a complex rect to be infinite. In both cases, D2D
// will handle clipping the inputs to the actual output rect area, if needed.
for (uint i = 0; i < inputRectsCount; i++)
else
{
switch (@this->inputTypes[i])
ReadOnlySpan<D2D1PixelShaderInputType> inputTypes = @this->GetGlobals().InputTypes.Span;
// If no custom transform is used, apply the default mapping. In this case, the loop will
// automatically handle cases where no inputs are defined. If inputs are present instead,
// the default mapping will set the input rect for a simple input to be the same as the
// output rect, and the input rect for a complex rect to be infinite. In both cases, D2D
// will handle clipping the inputs to the actual output rect area, if needed.
for (uint i = 0; i < inputRectsCount; i++)
{
case D2D1PixelShaderInputType.Simple:
inputRects[i] = *outputRect;
break;
case D2D1PixelShaderInputType.Complex:
inputRects[i].MakeD2D1Infinite();
break;
default:
return E.E_FAIL;
switch (inputTypes[(int)i])
{
case D2D1PixelShaderInputType.Simple:
inputRects[i] = *outputRect;
break;
case D2D1PixelShaderInputType.Complex:
inputRects[i].MakeD2D1Infinite();
break;
default:
return E.E_FAIL;
}
}
}
}
return S.S_OK;
return S.S_OK;
}
catch (Exception e)
{
return Marshal.GetHRForException(e);
}
}
/// <inheritdoc cref="ID2D1DrawTransform.MapInputRectsToOutputRect"/>
@@ -166,91 +176,90 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
if (inputRectCount != @this->inputCount)
try
{
return E.E_INVALIDARG;
}
default(ArgumentOutOfRangeException).ThrowIfNotEqual((int)inputRectCount, @this->GetGlobals().InputCount, nameof(inputRectCount));
if (@this->d2D1TransformMapper is not null)
{
using ComPtr<D2D1DrawInfoUpdateContextImpl> d2D1DrawInfoUpdateContext = default;
// Create an ID2D1DrawInfoUpdateContext instance
HRESULT hresult = D2D1DrawInfoUpdateContextImpl.Factory(
drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(),
constantBuffer: @this->constantBuffer,
constantBufferSize: @this->constantBufferSize,
d2D1DrawInfo: @this->d2D1DrawInfo);
if (!Windows.SUCCEEDED(hresult))
if (@this->d2D1TransformMapper is not null)
{
return hresult;
using ComPtr<D2D1DrawInfoUpdateContextImpl> d2D1DrawInfoUpdateContext = default;
// Create an ID2D1DrawInfoUpdateContext instance
D2D1DrawInfoUpdateContextImpl.Factory(
drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(),
constantBuffer: @this->constantBuffer,
constantBufferSize: @this->GetGlobals().ConstantBufferSize,
d2D1DrawInfo: @this->d2D1DrawInfo).Assert();
// Forward the call to the input ID2D1TransformMapper instance
HRESULT hresult = @this->d2D1TransformMapper->MapInputRectsToOutputRect(
updateContext: (ID2D1DrawInfoUpdateContext*)d2D1DrawInfoUpdateContext.Get(),
inputRects: inputRects,
inputOpaqueSubRects: inputOpaqueSubRects,
inputRectCount: inputRectCount,
outputRect: outputRect,
outputOpaqueSubRect: outputOpaqueSubRect);
// Regardless of the operation result, always invalidate the context
d2D1DrawInfoUpdateContext.Get()->Close().Assert();
// Now we can validate that the call was in fact successful
hresult.Assert();
}
// 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);
// Regardless of the operation result, always invalidate the context
_ = d2D1DrawInfoUpdateContext.Get()->Close();
if (!Windows.SUCCEEDED(hresult))
{
return hresult;
}
}
else if (inputRectCount == 0)
{
// If there are no inputs, make the output rectangle infinite. This is useful
// to make output-only effects work fine by default, without needing a custom
// transform. In this case, the target area will be the output node anyway.
outputRect->MakeD2D1Infinite();
*outputOpaqueSubRect = default;
}
else
{
// If at least one input is present and no custom mapper is available, apply the default
// mapping. In this case, the output rect should be the union of the input rects for all
// the simple shader inputs, or infinite if there are no simple inputs. The input rects
// for complex inputs, if present, are not needed in this scenario, so they're ignored.
RECT unionOfSimpleRects = default;
bool isUnionOfSimpleRectsEmpty = true;
for (uint i = 0; i < inputRectCount; i++)
{
if (@this->inputTypes[i] == D2D1PixelShaderInputType.Simple)
{
if (isUnionOfSimpleRectsEmpty)
{
unionOfSimpleRects = inputRects[i];
isUnionOfSimpleRectsEmpty = false;
}
else
{
unionOfSimpleRects = unionOfSimpleRects.Union(inputRects[i]);
}
}
}
if (isUnionOfSimpleRectsEmpty)
else if (inputRectCount == 0)
{
// If there are no inputs, make the output rectangle infinite. This is useful
// to make output-only effects work fine by default, without needing a custom
// transform. In this case, the target area will be the output node anyway.
outputRect->MakeD2D1Infinite();
*outputOpaqueSubRect = default;
}
else
{
*outputRect = unionOfSimpleRects;
ReadOnlySpan<D2D1PixelShaderInputType> inputTypes = @this->GetGlobals().InputTypes.Span;
// If at least one input is present and no custom mapper is available, apply the default
// mapping. In this case, the output rect should be the union of the input rects for all
// the simple shader inputs, or infinite if there are no simple inputs. The input rects
// for complex inputs, if present, are not needed in this scenario, so they're ignored.
RECT unionOfSimpleRects = default;
bool isUnionOfSimpleRectsEmpty = true;
for (uint i = 0; i < inputRectCount; i++)
{
if (inputTypes[(int)i] == D2D1PixelShaderInputType.Simple)
{
if (isUnionOfSimpleRectsEmpty)
{
unionOfSimpleRects = inputRects[i];
isUnionOfSimpleRectsEmpty = false;
}
else
{
unionOfSimpleRects = unionOfSimpleRects.Union(inputRects[i]);
}
}
}
if (isUnionOfSimpleRectsEmpty)
{
outputRect->MakeD2D1Infinite();
}
else
{
*outputRect = unionOfSimpleRects;
}
*outputOpaqueSubRect = default;
}
*outputOpaqueSubRect = default;
return S.S_OK;
}
catch (Exception e)
{
return Marshal.GetHRForException(e);
}
return S.S_OK;
}
/// <inheritdoc cref="ID2D1DrawTransform.MapInvalidRect"/>
@@ -259,39 +268,38 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
if (inputIndex >= (uint)@this->inputCount)
try
{
return E.E_INVALIDARG;
}
default(ArgumentOutOfRangeException).ThrowIfGreaterThanOrEqual((int)inputIndex, @this->GetGlobals().InputCount, nameof(inputIndex));
if (@this->d2D1TransformMapper is not null)
{
// Forward to the current ID2D1TransformMapper instance
HRESULT hresult = @this->d2D1TransformMapper->MapInvalidRect(inputIndex, invalidInputRect, invalidOutputRect);
if (!Windows.SUCCEEDED(hresult))
if (@this->d2D1TransformMapper is not null)
{
return hresult;
// Forward to the current ID2D1TransformMapper instance
@this->d2D1TransformMapper->MapInvalidRect(inputIndex, invalidInputRect, invalidOutputRect).Assert();
}
}
else
{
// The default mapping in this scenario just needs to set the invalid output rect for simple inputs to
// be the invalid input rect, and to set the invalid output rect for complex inputs to an infinite rect.
switch (@this->inputTypes[inputIndex])
else
{
case D2D1PixelShaderInputType.Simple:
*invalidOutputRect = invalidInputRect;
break;
case D2D1PixelShaderInputType.Complex:
invalidOutputRect->MakeD2D1Infinite();
break;
default:
return E.E_FAIL;
// The default mapping in this scenario just needs to set the invalid output rect for simple inputs to
// be the invalid input rect, and to set the invalid output rect for complex inputs to an infinite rect.
switch (@this->GetGlobals().InputTypes.Span[(int)inputIndex])
{
case D2D1PixelShaderInputType.Simple:
*invalidOutputRect = invalidInputRect;
break;
case D2D1PixelShaderInputType.Complex:
invalidOutputRect->MakeD2D1Infinite();
break;
default:
return E.E_FAIL;
}
}
}
return S.S_OK;
return S.S_OK;
}
catch (Exception e)
{
return Marshal.GetHRForException(e);
}
}
/// <inheritdoc cref="ID2D1DrawTransform.SetDrawInfo"/>
@@ -300,60 +308,45 @@ partial struct PixelShaderEffect
{
@this = (PixelShaderEffect*)&((void**)@this)[-1];
// Free the previous ID2D1DrawInfo object, if present
if (@this->d2D1DrawInfo is not null)
try
{
_ = @this->d2D1DrawInfo->Release();
}
// Store the new ID2D1DrawInfo object
ComPtr<ID2D1DrawInfo>.CopyTo(drawInfo, ref @this->d2D1DrawInfo);
// Store the new ID2D1DrawInfo object
_ = drawInfo->AddRef();
Guid shaderId = @this->GetGlobals().EffectId;
D2D1PixelOptions pixelOptions = @this->GetGlobals().PixelOptions;
@this->d2D1DrawInfo = drawInfo;
// Set the pixel shader for the effect
drawInfo->SetPixelShader(&shaderId, (D2D1_PIXEL_OPTIONS)pixelOptions).Assert();
// Set the pixel shader for the effect
HRESULT hresult = drawInfo->SetPixelShader(&@this->shaderId, (D2D1_PIXEL_OPTIONS)@this->pixelOptions);
if (hresult != S.S_OK)
{
return hresult;
}
// If any input descriptions are present, set them
if (@this->inputDescriptionCount > 0)
{
for (int i = 0; i < @this->inputDescriptionCount; i++)
// If any input descriptions are present, set them
foreach (ref readonly D2D1InputDescription inputDescription in @this->GetGlobals().InputDescriptions.Span)
{
ref D2D1InputDescription inputDescription = ref @this->inputDescriptions[i];
D2D1_INPUT_DESCRIPTION d2D1InputDescription;
d2D1InputDescription.filter = (D2D1_FILTER)inputDescription.Filter;
d2D1InputDescription.levelOfDetailCount = (uint)inputDescription.LevelOfDetailCount;
hresult = drawInfo->SetInputDescription((uint)inputDescription.Index, d2D1InputDescription);
if (hresult != S.S_OK)
{
return hresult;
}
drawInfo->SetInputDescription((uint)inputDescription.Index, d2D1InputDescription).Assert();
}
}
// If a custom buffer precision or channel depth is requested, set it
if (@this->bufferPrecision != D2D1BufferPrecision.Unknown ||
@this->channelDepth != D2D1ChannelDepth.Default)
{
hresult = drawInfo->SetOutputBuffer(
(D2D1_BUFFER_PRECISION)@this->bufferPrecision,
(D2D1_CHANNEL_DEPTH)@this->channelDepth);
D2D1BufferPrecision bufferPrecision = @this->GetGlobals().BufferPrecision;
D2D1ChannelDepth channelDepth = @this->GetGlobals().ChannelDepth;
if (hresult != S.S_OK)
// If a custom buffer precision or channel depth is requested, set it
if (bufferPrecision != D2D1BufferPrecision.Unknown ||
channelDepth != D2D1ChannelDepth.Default)
{
return hresult;
drawInfo->SetOutputBuffer(
(D2D1_BUFFER_PRECISION)bufferPrecision,
(D2D1_CHANNEL_DEPTH)channelDepth).Assert();
}
}
return S.S_OK;
return S.S_OK;
}
catch (Exception e)
{
return Marshal.GetHRForException(e);
}
}
}
}
+64 -72
ファイルの表示
@@ -1,5 +1,6 @@
using System;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.Extensions;
using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers;
using ComputeSharp.D2D1.Shaders.Interop.Extensions;
using TerraFX.Interop.DirectX;
@@ -86,115 +87,106 @@ internal unsafe partial struct PixelShaderEffect
[UnmanagedCallersOnly]
public static int Initialize(PixelShaderEffect* @this, ID2D1EffectContext* effectContext, ID2D1TransformGraph* transformGraph)
{
int hresult = effectContext->LoadPixelShader(
shaderId: &@this->shaderId,
shaderBuffer: @this->bytecode,
shaderBufferCount: (uint)@this->bytecodeSize);
// If E_INVALIDARG was returned, try to check whether double precision support was requested when not available. This
// is only done to provide a more helpful error message to callers. If no error was returned, the behavior is the same.
// If any error is detected while trying to check for shader support, ignore the value and propagate the current HRESULT.
if (hresult == E.E_INVALIDARG && effectContext->IsShaderSupported(@this->bytecode, @this->bytecodeSize) == S.S_FALSE)
try
{
hresult = D2DERR.D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES;
}
ReadOnlySpan<byte> bytecode = @this->GetGlobals().HlslBytecode.Span;
// If loading the bytecode succeeded, set the transform node
if (Windows.SUCCEEDED(hresult))
{
hresult = transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform);
}
// If the transform node was set, also store the effect context
if (Windows.SUCCEEDED(hresult))
{
// Free the previous ID2D1EffectContext object, if present
if (@this->d2D1EffectContext is not null)
fixed (Guid* pShaderId = &@this->GetGlobals().EffectId)
fixed (byte* pBytecode = bytecode)
{
_ = @this->d2D1EffectContext->Release();
HRESULT hresult = effectContext->LoadPixelShader(
shaderId: pShaderId,
shaderBuffer: pBytecode,
shaderBufferCount: (uint)bytecode.Length);
// If E_INVALIDARG was returned, try to check whether double precision support was requested when not available. This
// is only done to provide a more helpful error message to callers. If no error was returned, the behavior is the same.
// If any error is detected while trying to check for shader support, ignore the value and propagate the current HRESULT.
if (hresult == E.E_INVALIDARG && effectContext->IsShaderSupported(pBytecode, bytecode.Length) == S.S_FALSE)
{
hresult = D2DERR.D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES;
}
// Finally, assert that we did load the pixel shader correctly
hresult.Assert();
}
// If loading the bytecode succeeded, set the transform node
transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform).Assert();
// Store the new ID2D1EffectContext object
_ = effectContext->AddRef();
ComPtr<ID2D1EffectContext>.CopyTo(effectContext, ref @this->d2D1EffectContext);
@this->d2D1EffectContext = effectContext;
return S.S_OK;
}
catch (Exception e)
{
return Marshal.GetHRForException(e);
}
return hresult;
}
/// <inheritdoc cref="ID2D1EffectImpl.PrepareForRender"/>
[UnmanagedCallersOnly]
public static int PrepareForRender(PixelShaderEffect* @this, D2D1_CHANGE_TYPE changeType)
{
int hresult = S.S_OK;
// Validate the constant buffer
if (@this->constantBufferSize > 0 &&
@this->constantBuffer is null)
try
{
return E.E_NOT_VALID_STATE;
}
// Validate the constant buffer. We either must have a stateless shader, in which case
// the constant buffer might either be null or empty (both cases are allowed), or we
// must have a shader with some state and a constant buffer being set. In that case
// the code setting the constant buffer will have already validated its length.
if (@this->GetGlobals().ConstantBufferSize > 0 &&
@this->constantBuffer is null)
{
return E.E_NOT_VALID_STATE;
}
// First, set the constant buffer, if available
if (@this->constantBuffer is not null)
{
hresult = @this->d2D1DrawInfo->SetPixelShaderConstantBuffer(
buffer: @this->constantBuffer,
bufferCount: (uint)@this->constantBufferSize);
}
// First, set the constant buffer, if available
if (@this->constantBuffer is not null)
{
@this->d2D1DrawInfo->SetPixelShaderConstantBuffer(
buffer: @this->constantBuffer,
bufferCount: (uint)@this->GetGlobals().ConstantBufferSize).Assert();
}
if (Windows.SUCCEEDED(hresult))
{
for (int i = 0; i < @this->resourceTextureDescriptionCount; i++)
ReadOnlySpan<D2D1ResourceTextureDescription> resourceTextureDescriptions = @this->GetGlobals().ResourceTextureDescriptions.Span;
for (int i = 0; i < resourceTextureDescriptions.Length; i++)
{
using ComPtr<ID2D1ResourceTextureManager> resourceTextureManager = @this->resourceTextureManagerBuffer[i];
// If the current resource texture manager is not set, we cannot render, as there's an unbound resource texture
if (resourceTextureManager.Get() is null)
{
hresult = E.E_NOT_VALID_STATE;
break;
return E.E_NOT_VALID_STATE;
}
using ComPtr<ID2D1ResourceTextureManagerInternal> resourceTextureManagerInternal = default;
// Get the ID2D1ResourceTextureManagerInternal object
hresult = resourceTextureManager.CopyTo(resourceTextureManagerInternal.GetAddressOf());
// This cast should always succeed, as when an input resource texture managers is set it's
// also checked for ID2D1ResourceTextureManagerInternal, but still validate for good measure.
if (!Windows.SUCCEEDED(hresult))
{
break;
}
// Get the ID2D1ResourceTextureManagerInternal object. This cast should always succeed, as when
// an input resource texture managers is set it's also checked for ID2D1ResourceTextureManagerInternal,
// but still validate for good measure.
resourceTextureManager.CopyTo(resourceTextureManagerInternal.GetAddressOf()).Assert();
using ComPtr<ID2D1ResourceTexture> d2D1ResourceTexture = default;
// Try to get the ID2D1ResourceTexture from the manager
hresult = resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf());
resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf()).Assert();
if (!Windows.SUCCEEDED(hresult))
{
break;
}
ref readonly D2D1ResourceTextureDescription resourceTextureDescription = ref @this->resourceTextureDescriptions[i];
ref readonly D2D1ResourceTextureDescription resourceTextureDescription = ref resourceTextureDescriptions[i];
// Set the ID2D1ResourceTexture object to the current index in the ID2D1DrawInfo object in use
hresult = @this->d2D1DrawInfo->SetResourceTexture(
@this->d2D1DrawInfo->SetResourceTexture(
textureIndex: (uint)resourceTextureDescription.Index,
resourceTexture: d2D1ResourceTexture.Get());
if (!Windows.SUCCEEDED(hresult))
{
break;
}
resourceTexture: d2D1ResourceTexture.Get()).Assert();
}
}
return hresult;
return S.S_OK;
}
catch (Exception e)
{
return Marshal.GetHRForException(e);
}
}
/// <inheritdoc cref="ID2D1EffectImpl.SetGraph"/>
+155 -199
ファイルの表示
@@ -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 ComputeSharp.D2D1.Shaders.Interop.Effects.TransformMappers;
using TerraFX.Interop.DirectX;
@@ -115,46 +116,51 @@ unsafe partial struct PixelShaderEffect
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
// This is a call likely from ID2D1Effect::GetValueSize, to query the property size
if (data is null &&
dataSize == 0 &&
actualSize is not null)
try
{
*actualSize = (uint)@this->constantBufferSize;
// This is a call likely from ID2D1Effect::GetValueSize, to query the property size.
// In that case we explicitly allow these inputs, and return the size of the buffer.
if (data is null &&
dataSize == 0 &&
actualSize is not null)
{
*actualSize = (uint)@this->GetGlobals().ConstantBufferSize;
return S.S_FALSE;
return S.S_FALSE;
}
default(ArgumentNullException).ThrowIfNull(data);
if (dataSize < @this->GetGlobals().ConstantBufferSize)
{
return E.E_NOT_SUFFICIENT_BUFFER;
}
if (@this->constantBuffer is null)
{
return E.E_NOT_VALID_STATE;
}
uint writtenBytes = 0;
if (@this->GetGlobals().ConstantBufferSize > 0)
{
Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, @this->GetGlobals().ConstantBufferSize);
writtenBytes = (uint)@this->GetGlobals().ConstantBufferSize;
}
if (actualSize is not null)
{
*actualSize = writtenBytes;
}
return S.S_OK;
}
if (data is null)
catch (Exception e)
{
return E.E_POINTER;
return Marshal.GetHRForException(e);
}
if (dataSize < @this->constantBufferSize)
{
return E.E_NOT_SUFFICIENT_BUFFER;
}
if (@this->constantBuffer is null)
{
return E.E_NOT_VALID_STATE;
}
uint writtenBytes = 0;
if (@this->constantBufferSize > 0)
{
Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, @this->constantBufferSize);
writtenBytes = (uint)@this->constantBufferSize;
}
if (actualSize is not null)
{
*actualSize = writtenBytes;
}
return S.S_OK;
}
/// <inheritdoc cref="D2D1_PROPERTY_BINDING.getFunction"/>
@@ -163,31 +169,31 @@ unsafe partial struct PixelShaderEffect
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
if (data is null)
try
{
return E.E_POINTER;
}
default(ArgumentNullException).ThrowIfNull(data);
default(ArgumentOutOfRangeException).ThrowIfNotEqual((int)dataSize, @this->GetGlobals().ConstantBufferSize, nameof(dataSize));
if (dataSize != (uint)@this->constantBufferSize)
// Reuse the existing buffer if there is one, otherwise allocate a new one
if (@this->constantBuffer is not null)
{
Buffer.MemoryCopy(data, @this->constantBuffer, dataSize, dataSize);
}
else
{
void* buffer = NativeMemory.Alloc(dataSize);
Buffer.MemoryCopy(data, buffer, dataSize, dataSize);
@this->constantBuffer = (byte*)buffer;
}
return S.S_OK;
}
catch (Exception e)
{
return E.E_INVALIDARG;
return Marshal.GetHRForException(e);
}
// Reuse the existing buffer if there is one, otherwise allocate a new one
if (@this->constantBuffer is not null)
{
Buffer.MemoryCopy(data, @this->constantBuffer, dataSize, dataSize);
}
else
{
void* buffer = NativeMemory.Alloc(dataSize);
Buffer.MemoryCopy(data, buffer, dataSize, dataSize);
@this->constantBuffer = (byte*)buffer;
}
return S.S_OK;
}
/// <inheritdoc cref="D2D1_PROPERTY_BINDING.getFunction"/>
@@ -196,36 +202,31 @@ unsafe partial struct PixelShaderEffect
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
if (data is null)
try
{
return E.E_POINTER;
}
default(ArgumentNullException).ThrowIfNull(data);
default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize));
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))
if (@this->d2D1TransformMapper is null)
{
return hresult;
*(void**)data = null;
}
else
{
((IUnknown*)@this->d2D1TransformMapper)->QueryInterface(Windows.__uuidof<ID2D1TransformMapper>(), (void**)data).Assert();
}
}
if (actualSize is not null)
if (actualSize is not null)
{
*actualSize = (uint)sizeof(void*);
}
return S.S_OK;
}
catch (Exception e)
{
*actualSize = (uint)sizeof(void*);
return Marshal.GetHRForException(e);
}
return S.S_OK;
}
/// <inheritdoc cref="D2D1_PROPERTY_BINDING.getFunction"/>
@@ -234,44 +235,33 @@ unsafe partial struct PixelShaderEffect
{
PixelShaderEffect* @this = (PixelShaderEffect*)effect;
if (data is null)
try
{
return E.E_POINTER;
default(ArgumentNullException).ThrowIfNull(data);
default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize));
void* value = *(void**)data;
default(ArgumentNullException).ThrowIfNull(value);
using ComPtr<IUnknown> unknown = (IUnknown*)value;
using ComPtr<ID2D1TransformMapper> transformMapper = default;
// Check that the input object implements ID2D1TransformMapper
unknown.CopyTo(transformMapper.GetAddressOf()).Assert();
// If there's already an existing manager, release it
ComPtr<ID2D1TransformMapper>.Release(@this->d2D1TransformMapper);
// Store the transform mapper manager into the effect
@this->d2D1TransformMapper = transformMapper.Detach();
return S.S_OK;
}
void* value = *(void**)data;
if (value is null)
catch (Exception e)
{
return E.E_POINTER;
return Marshal.GetHRForException(e);
}
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;
}
/// <summary>
@@ -284,36 +274,27 @@ unsafe partial struct PixelShaderEffect
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
private int GetResourceTextureManagerAtIndex(int index, byte* data, uint dataSize, uint* actualSize)
{
if (index >= this.resourceTextureDescriptionCount)
try
{
return E.E_INVALIDARG;
}
default(ArgumentNullException).ThrowIfNull(data);
default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize));
default(ArgumentOutOfRangeException).ThrowIfGreaterThanOrEqual(index, GetGlobals().ResourceTextureCount);
if (data is null)
using ComPtr<ID2D1ResourceTextureManager> resourceTextureManager = this.resourceTextureManagerBuffer[index];
resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data).Assert();
if (actualSize is not null)
{
*actualSize = (uint)sizeof(void*);
}
return S.S_OK;
}
catch (Exception e)
{
return E.E_POINTER;
return Marshal.GetHRForException(e);
}
if (dataSize < sizeof(void*))
{
return E.E_INVALIDARG;
}
using ComPtr<ID2D1ResourceTextureManager> resourceTextureManager = this.resourceTextureManagerBuffer[index];
HRESULT hresult = resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data);
if (!Windows.SUCCEEDED(hresult))
{
return hresult;
}
if (actualSize is not null)
{
*actualSize = (uint)sizeof(void*);
}
return S.S_OK;
}
/// <summary>
@@ -325,78 +306,53 @@ unsafe partial struct PixelShaderEffect
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
private int SetResourceTextureManagerAtIndex(int index, byte* data, uint dataSize)
{
if (index >= this.resourceTextureDescriptionCount)
try
{
return E.E_INVALIDARG;
}
default(ArgumentNullException).ThrowIfNull(data);
default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize));
default(ArgumentOutOfRangeException).ThrowIfGreaterThanOrEqual(index, GetGlobals().ResourceTextureCount);
if (data is null)
{
return E.E_POINTER;
}
void* value = *(void**)data;
void* value = *(void**)data;
default(ArgumentNullException).ThrowIfNull(value);
if (value is null)
{
return E.E_POINTER;
}
using ComPtr<IUnknown> unknown = (IUnknown*)value;
using ComPtr<ID2D1ResourceTextureManager> resourceTextureManager = default;
if (dataSize != (uint)sizeof(void*))
{
return E.E_INVALIDARG;
}
// Check that the input object implements ID2D1ResourceTextureManager
unknown.CopyTo(resourceTextureManager.GetAddressOf()).Assert();
using ComPtr<IUnknown> unknown = (IUnknown*)value;
using ComPtr<ID2D1ResourceTextureManager> resourceTextureManager = default;
using ComPtr<ID2D1ResourceTextureManagerInternal> resourceTextureManagerInternal = default;
// Check that the input object implements ID2D1ResourceTextureManager
int result = unknown.CopyTo(resourceTextureManager.GetAddressOf());
// Then, also check that it implements ID2D1ResourceTextureManagerInternal
unknown.CopyTo(resourceTextureManagerInternal.GetAddressOf()).Assert();
if (result != S.S_OK)
{
return result;
}
using ComPtr<ID2D1ResourceTextureManagerInternal> resourceTextureManagerInternal = default;
// Then, also check that it implements ID2D1ResourceTextureManagerInternal
result = unknown.CopyTo(resourceTextureManagerInternal.GetAddressOf());
if (result != S.S_OK)
{
return result;
}
// Initialize the resource texture manager, if an effect context is available
if (this.d2D1EffectContext is not null)
{
uint dimensions = (uint)this.resourceTextureDescriptions[index].Dimensions;
result = resourceTextureManagerInternal.Get()->Initialize(this.d2D1EffectContext, &dimensions);
// ID2D1ResourceTextureManager::Initialize should generally return either S_OK for first
// initialization, S_FALSE if an ID2D1EffectContext is already present (which is allowed, to
// enable sharing resource texture managers across different source textures and effects), or
// E_INVALIDARG if the manager has already been initialized through the public interface,
// and the stored dimensions for that don't match the ones for this resource texture index.
if (!Windows.SUCCEEDED(result))
// Initialize the resource texture manager, if an effect context is available
if (this.d2D1EffectContext is not null)
{
return result;
uint dimensions = (uint)GetGlobals().ResourceTextureDescriptions.Span[index].Dimensions;
// ID2D1ResourceTextureManager::Initialize should generally return either S_OK for first
// initialization, S_FALSE if an ID2D1EffectContext is already present (which is allowed, to
// enable sharing resource texture managers across different source textures and effects), or
// E_INVALIDARG if the manager has already been initialized through the public interface,
// and the stored dimensions for that don't match the ones for this resource texture index.
resourceTextureManagerInternal.Get()->Initialize(this.d2D1EffectContext, &dimensions).Assert();
}
ref ID2D1ResourceTextureManager* currentResourceTextureManager = ref this.resourceTextureManagerBuffer[index];
// If there's already an existing manager at this index, release it
ComPtr<ID2D1ResourceTextureManager>.Release(currentResourceTextureManager);
// Store the resource texture manager into the buffer
currentResourceTextureManager = resourceTextureManager.Detach();
return S.S_OK;
}
ref ID2D1ResourceTextureManager* currentResourceTextureManager = ref this.resourceTextureManagerBuffer[index];
// If there's already an existing manager at this index, release it
if (currentResourceTextureManager is not null)
catch (Exception e)
{
_ = ((IUnknown*)currentResourceTextureManager)->Release();
return Marshal.GetHRForException(e);
}
// Store the resource texture manager into the buffer
currentResourceTextureManager = resourceTextureManager.Detach();
return S.S_OK;
}
}
+53 -158
ファイルの表示
@@ -106,86 +106,15 @@ internal unsafe partial struct PixelShaderEffect
private volatile int referenceCount;
/// <summary>
/// The <see cref="Guid"/> for the shader.
/// The <see cref="GCHandle"/> for the <see cref="Globals"/> instance in use.
/// </summary>
private Guid shaderId;
private GCHandle globalsHandle;
/// <summary>
/// The constant buffer data, if set.
/// </summary>
private byte* constantBuffer;
/// <summary>
/// The size of <see cref="constantBuffer"/>.
/// </summary>
private int constantBufferSize;
/// <summary>
/// The number of inputs for the shader.
/// </summary>
private int inputCount;
/// <summary>
/// The buffer with the types of inputs for the shader.
/// </summary>
/// <remarks>
/// This buffer is shared among effect instances, so it should not be released. It is
/// owned by <see cref="For{T}"/>, which will release it when the target type is unloaded.
/// </remarks>
private D2D1PixelShaderInputType* inputTypes;
/// <summary>
/// The number of available input descriptions.
/// </summary>
private int inputDescriptionCount;
/// <summary>
/// The buffer with the available input descriptions for the shader.
/// </summary>
/// <remarks>
/// This buffer is also shared among effect instances, so it should not be released. It is
/// owned by <see cref="For{T}"/>, which will release it when the target type is unloaded.
/// </remarks>
private D2D1InputDescription* inputDescriptions;
/// <summary>
/// The pixel options for the shader.
/// </summary>
private D2D1PixelOptions pixelOptions;
/// <summary>
/// The shader bytecode.
/// </summary>
private byte* bytecode;
/// <summary>
/// The size of <see cref="bytecode"/>.
/// </summary>
private int bytecodeSize;
/// <summary>
/// The buffer precision for the resulting output buffer.
/// </summary>
private D2D1BufferPrecision bufferPrecision;
/// <summary>
/// The channel depth for the resulting output buffer.
/// </summary>
private D2D1ChannelDepth channelDepth;
/// <summary>
/// The number of available resource texture descriptions.
/// </summary>
private int resourceTextureDescriptionCount;
/// <summary>
/// The buffer with the available resource texture descriptions for the shader.
/// </summary>
/// <remarks>
/// This buffer is also shared among effect instances, like <see cref="inputDescriptions"/>.
/// </remarks>
private D2D1ResourceTextureDescription* resourceTextureDescriptions;
/// <summary>
/// The <see cref="ID2D1TransformMapper"/> instance to use, if any.
/// </summary>
@@ -209,77 +138,48 @@ internal unsafe partial struct PixelShaderEffect
/// <summary>
/// The factory method for <see cref="ID2D1Factory1.RegisterEffectFromString"/>.
/// </summary>
/// <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>
/// <param name="globals">The <see cref="Globals"/> instance to use.</param>
/// <param name="effectImpl">The resulting effect instance.</param>
/// <returns>This always returns <c>0</c>.</returns>
private static int Factory(
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,
IUnknown** effectImpl)
/// <returns>The <see cref="HRESULT"/> for the operation.</returns>
private static int Factory(Globals globals, IUnknown** effectImpl)
{
PixelShaderEffect* @this;
PixelShaderEffect* @this = null;
GCHandle globalsHandle = default;
try
{
@this = (PixelShaderEffect*)NativeMemory.Alloc((nuint)sizeof(PixelShaderEffect));
globalsHandle = GCHandle.Alloc(globals);
@this->lpVtblForID2D1EffectImpl = VtblForID2D1EffectImpl;
@this->lpVtblForID2D1DrawTransform = VtblForID2D1DrawTransform;
@this->referenceCount = 1;
@this->globalsHandle = globalsHandle;
@this->constantBuffer = null;
@this->d2D1TransformMapper = null;
@this->d2D1DrawInfo = null;
@this->d2D1EffectContext = null;
@this->resourceTextureManagerBuffer = default;
*effectImpl = (IUnknown*)@this;
return S.S_OK;
}
catch (OutOfMemoryException)
catch (Exception e)
{
// Free the effect, if we have one
NativeMemory.Free(@this);
// Free the handle, if we have one
if (globalsHandle.IsAllocated)
{
globalsHandle.Free();
}
*effectImpl = null;
return E.E_OUTOFMEMORY;
return Marshal.GetHRForException(e);
}
*@this = default;
@this->lpVtblForID2D1EffectImpl = VtblForID2D1EffectImpl;
@this->lpVtblForID2D1DrawTransform = VtblForID2D1DrawTransform;
@this->referenceCount = 1;
@this->shaderId = shaderId;
@this->constantBuffer = null;
@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;
@this->d2D1TransformMapper = null;
@this->d2D1DrawInfo = null;
@this->d2D1EffectContext = null;
@this->resourceTextureManagerBuffer = default;
*effectImpl = (IUnknown*)@this;
return S.S_OK;
}
/// <inheritdoc cref="IUnknown.QueryInterface"/>
@@ -331,35 +231,20 @@ internal unsafe partial struct PixelShaderEffect
if (referenceCount == 0)
{
if (this.constantBuffer is not null)
{
NativeMemory.Free(this.constantBuffer);
}
this.globalsHandle.Free();
if (this.d2D1TransformMapper is not null)
{
_ = ((IUnknown*)this.d2D1TransformMapper)->Release();
}
NativeMemory.Free(this.constantBuffer);
if (this.d2D1DrawInfo is not null)
{
_ = this.d2D1DrawInfo->Release();
}
ComPtr<ID2D1TransformMapper>.Release(this.d2D1TransformMapper);
ComPtr<ID2D1DrawInfo>.Release(this.d2D1DrawInfo);
ComPtr<ID2D1EffectContext>.Release(this.d2D1EffectContext);
if (this.d2D1EffectContext is not null)
// Retrieve all possible resource texture managers in use and release the ones that had been
// assigned (from one of the property bindings). We just hardcode 16 here and dont access
// the globals, as technically invoking APIs on it might throw an exception.
for (int i = 0; i < 16; i++)
{
_ = this.d2D1EffectContext->Release();
}
// Retrieve all possible resource texture managers in use and release the ones that had been assigned (from one of the property bindings)
for (int i = 0; i < this.resourceTextureDescriptionCount; i++)
{
ID2D1ResourceTextureManager* resourceTextureManager = this.resourceTextureManagerBuffer[i];
if (resourceTextureManager is not null)
{
_ = ((IUnknown*)resourceTextureManager)->Release();
}
ComPtr<ID2D1ResourceTextureManager>.Release(this.resourceTextureManagerBuffer[i]);
}
NativeMemory.Free(Unsafe.AsPointer(ref this));
@@ -367,4 +252,14 @@ internal unsafe partial struct PixelShaderEffect
return referenceCount;
}
/// <summary>
/// Gets the <see cref="Globals"/> instance for the current effect.
/// </summary>
/// <returns>The <see cref="Globals"/> instance for the current effect.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Globals GetGlobals()
{
return Unsafe.As<Globals>(this.globalsHandle.Target!);
}
}
@@ -124,9 +124,8 @@ partial struct D2D1ResourceTextureManagerImpl
// Now, the effect context can actually be stored safely while holding the lock.
// This is guaranteed to be the case here, as this method is only called (as per
// contact of the COM interface) from ID2D1EffectImpl, which holds the D2D lock.
_ = effectContext->AddRef();
ComPtr<ID2D1EffectContext>.WriteTo(effectContext, out @this->d2D1EffectContext);
@this->d2D1EffectContext = effectContext;
@this->d2D1Multithread = d2D1Multithread.Detach();
}
@@ -162,9 +161,7 @@ partial struct D2D1ResourceTextureManagerImpl
// If the texture has already been created, just return it
if (@this->d2D1ResourceTexture is not null)
{
_ = @this->d2D1ResourceTexture->AddRef();
*resourceTexture = @this->d2D1ResourceTexture;
ComPtr<ID2D1ResourceTexture>.WriteTo(@this->d2D1ResourceTexture, out *resourceTexture);
return S.S_OK;
}
@@ -247,10 +247,7 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl
this.d2D1Multithread->Enter();
// Release the resource too if it has been created
if (this.d2D1ResourceTexture is not null)
{
_ = this.d2D1ResourceTexture->Release();
}
ComPtr<ID2D1ResourceTexture>.Release(this.d2D1ResourceTexture);
// Now that the resource, if any, has been released, the effect context can also
// be released. This must be done only after any associated resource textures have
@@ -263,30 +260,11 @@ internal unsafe partial struct D2D1ResourceTextureManagerImpl
_ = this.d2D1Multithread->Release();
}
if (this.resourceId is not null)
{
NativeMemory.Free(this.resourceId);
}
if (this.resourceTextureProperties.extents is not null)
{
NativeMemory.Free(this.resourceTextureProperties.extents);
}
if (this.resourceTextureProperties.extendModes is not null)
{
NativeMemory.Free(this.resourceTextureProperties.extendModes);
}
if (this.data is not null)
{
NativeMemory.Free(this.data);
}
if (this.strides is not null)
{
NativeMemory.Free(this.strides);
}
NativeMemory.Free(this.resourceId);
NativeMemory.Free(this.resourceTextureProperties.extents);
NativeMemory.Free(this.resourceTextureProperties.extendModes);
NativeMemory.Free(this.data);
NativeMemory.Free(this.strides);
}
this.lockHandle.Free();
@@ -131,7 +131,7 @@ unsafe partial struct D2D1TransformMapperImpl
}
catch (Exception e)
{
return e.HResult;
return Marshal.GetHRForException(e);
}
*outputRect = output.ToRECT();
@@ -163,7 +163,7 @@ unsafe partial struct D2D1TransformMapperImpl
}
catch (Exception e)
{
return e.HResult;
return Marshal.GetHRForException(e);
}
for (int i = 0; i < (int)inputRectsCount; i++)
@@ -192,7 +192,7 @@ unsafe partial struct D2D1TransformMapperImpl
}
catch (Exception e)
{
return e.HResult;
return Marshal.GetHRForException(e);
}
*invalidOutputRect = invalidOutput.ToRECT();
+1 -1
ファイルの表示
@@ -165,7 +165,7 @@ internal unsafe struct ID3D12MemoryAllocatorFactoryImpl
}
catch (Exception e)
{
return e.HResult;
return Marshal.GetHRForException(e);
}
}
}
-46
ファイルの表示
@@ -8,52 +8,6 @@ namespace ComputeSharp.Core.Extensions;
/// </summary>
internal static class ComPtrExtensions
{
#if NET6_0_OR_GREATER
/// <summary>
/// Invokes <see cref="IUnknown.AddRef"/> on the wrapped object for an input <see cref="ComPtr{T}"/> value.
/// </summary>
/// <typeparam name="T">The type of the current <see cref="ComPtr{T}"/> instance.</typeparam>
/// <param name="ptr">The input <see cref="ComPtr{T}"/> instance to increment the reference count for.</param>
/// <returns>A <see cref="ComPtr{T}"/> instance of type <see cref="IUnknown"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe uint AddRef<T>(this ComPtr<T> ptr)
where T : unmanaged, IUnknown.Interface
{
if (ptr.Get() is not null)
{
return ptr.Get()->AddRef();
}
return 0;
}
/// <summary>
/// Invokes <see cref="IUnknown.Release"/> on the wrapped object for an input <see cref="ComPtr{T}"/> value.
/// If the object has been deleted, it also resets <paramref name="ptr"/>.
/// </summary>
/// <typeparam name="T">The type of the current <see cref="ComPtr{T}"/> instance.</typeparam>
/// <param name="ptr">The input <see cref="ComPtr{T}"/> instance to release.</param>
/// <returns>A <see cref="ComPtr{T}"/> instance of type <see cref="IUnknown"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe uint Release<T>(this ref ComPtr<T> ptr)
where T : unmanaged, IUnknown.Interface
{
if (ptr.Get() is not null)
{
uint count = ptr.Get()->Release();
if (count == 0)
{
ptr = default;
}
return count;
}
return 0;
}
#endif
/// <summary>
/// Reinterprets the current <see cref="ComPtr{T}"/> instance as one of type <see cref="IUnknown"/>.
/// </summary>
+2 -2
ファイルの表示
@@ -373,7 +373,7 @@ unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
return ex.HResult;
return Marshal.GetHRForException(ex);
}
}
@@ -454,7 +454,7 @@ unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
return ex.HResult;
return Marshal.GetHRForException(ex);
}
}
+6 -6
ファイルの表示
@@ -380,7 +380,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
return ex.HResult;
return Marshal.GetHRForException(ex);
}
}
@@ -416,7 +416,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
return ex.HResult;
return Marshal.GetHRForException(ex);
}
}
@@ -454,7 +454,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
return ex.HResult;
return Marshal.GetHRForException(ex);
}
}
@@ -475,7 +475,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
return ex.HResult;
return Marshal.GetHRForException(ex);
}
}
@@ -498,7 +498,7 @@ internal static unsafe partial class IWICStreamExtensions
}
catch (Exception ex)
{
return ex.HResult;
return Marshal.GetHRForException(ex);
}
}
@@ -587,7 +587,7 @@ internal static unsafe partial class IWICStreamExtensions
pstatstg->pwcsName = null;
}
return ex.HResult;
return Marshal.GetHRForException(ex);
}
}
+56
ファイルの表示
@@ -38,6 +38,62 @@ internal unsafe struct ComPtr<T> : IDisposable
InternalAddRef();
}
/// <summary>
/// Releases a target COM object, if it's not <see langword="null"/>.
/// </summary>
/// <param name="other">The COM object to potentially release.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Release(T* other)
{
if (other is not null)
{
_ = ((IUnknown*)other)->Release();
}
}
/// <summary>
/// Copies a given COM object into a target destination, incrementing reference counts where needed.
/// </summary>
/// <param name="obj">The input COM object to copy.</param>
/// <param name="other">The target destination for the COM object.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CopyTo(T* obj, ref T* other)
{
// We specifically need to increment the reference count on the source object before releasing the
// target object, to avoid issues in case source and destination were pointers to the same object
// (which can be the case even if the two pointers are not identical). To double check, a full check
// through an IUnknown* cast would be needed, but to avoid the extra QueryInterface call on both objects,
// we can just always do one AddRef call which avoids issues in all cases as well. The situation we need
// to avoid is that without a temporary copy, releasing the target object might actually destroy the
// object, causing the following AddRef call to AV.
if (obj is not null)
{
_ = ((IUnknown*)obj)->AddRef();
}
T* pointer = other;
if (pointer is not null)
{
_ = ((IUnknown*)pointer)->Release();
}
other = obj;
}
/// <summary>
/// Writes a given COM object into a target (assumed uninitialized) destination, incrementing reference counts where needed.
/// </summary>
/// <param name="obj">The input COM object to copy.</param>
/// <param name="other">The target destination for the COM object.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteTo(T* obj, out T* other)
{
_ = ((IUnknown*)obj)->AddRef();
other = obj;
}
/// <summary>Converts a raw pointer to a new <see cref="ComPtr{T}"/> instance and increments the ref count.</summary>
/// <param name="other">The raw pointer to wrap.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]