From 73c492ba2b9b6eaa72dc979932a03e8ae3a489f9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 5 Oct 2023 10:34:30 +0200 Subject: [PATCH 01/11] Refactor shared state for built-in pixel shader effect --- ...derEffect{T}.ICanvasEffectFactoryNative.cs | 4 +- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 3 +- .../Shaders/Interop/D2D1PixelShaderEffect.cs | 16 +- .../Effects/PixelShaderEffect.For{T}.cs | 299 ++++++------------ ...lShaderEffect.ID2D1DrawTransformMethods.cs | 59 ++-- ...ixelShaderEffect.ID2D1EffectImplMethods.cs | 35 +- .../Effects/PixelShaderEffect.Properties.cs | 18 +- .../Interop/Effects/PixelShaderEffect.cs | 159 +++------- 8 files changed, 213 insertions(+), 380 deletions(-) diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs index a894c2f2..0fcc7e0e 100644 --- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs +++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs @@ -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 if (!this.isEffectFactoryRegistered) { ResourceManager.RegisterEffectFactory( - effectId: PixelShaderEffect.For.Instance.Id, + effectId: D2D1PixelShaderEffect.GetEffectId(), factory: new EffectFactory()); this.isEffectFactoryRegistered = true; diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasImageInterop.cs index 796bd28a..f63e388e 100644 --- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasImageInterop.cs +++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -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 { fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect) { - Guid effectId = PixelShaderEffect.For.Instance.Id; + Guid effectId = D2D1PixelShaderEffect.GetEffectId(); using ComPtr d2D1DeviceContextEffective = default; using ComPtr d2D1DeviceContextLease = default; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index 46941807..7e9dcbfb 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -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.Instance.Id) + fixed (Guid* pGuid = &GetEffectId()) { // 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()), - effectFactory: PixelShaderEffect.For.Instance.Factory).Assert(); + effectFactory: PixelShaderEffect.Globals.Instance.Factory).Assert(); } - effectId = PixelShaderEffect.For.Instance.Id; + effectId = GetEffectId(); } } @@ -250,8 +250,8 @@ public static unsafe class D2D1PixelShaderEffect writer.Write(D2D1EffectRegistrationData.V1.BlobId); // Effect id and number of inputs - writer.Write(PixelShaderEffect.For.Instance.Id); - writer.Write(PixelShaderEffect.For.Instance.InputCount); + writer.Write(GetEffectId()); + writer.Write(D2D1PixelShader.GetInputCount()); // Retrieve the effect XML and include it into the registration blob using (D2D1EffectXmlFactory.EffectXml effectXml = D2D1EffectXmlFactory.GetXmlBuffer()) @@ -388,14 +388,14 @@ public static unsafe class D2D1PixelShaderEffect } // Effect factory - writer.Write((nint)PixelShaderEffect.For.Instance.Factory); + writer.Write((nint)PixelShaderEffect.Globals.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.Instance.Id; + effectId = GetEffectId(); return registrationBlob; } @@ -419,7 +419,7 @@ public static unsafe class D2D1PixelShaderEffect default(ArgumentNullException).ThrowIfNull(d2D1DeviceContext); default(ArgumentNullException).ThrowIfNull(d2D1Effect); - fixed (Guid* pGuid = &PixelShaderEffect.For.Instance.Id) + fixed (Guid* pGuid = &GetEffectId()) { ((ID2D1DeviceContext*)d2D1DeviceContext)->CreateEffect( effectId: pGuid, diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs index d9eba121..bc728ef2 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs @@ -4,9 +4,6 @@ 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; @@ -21,210 +18,59 @@ internal unsafe partial struct PixelShaderEffect /// The resulting effect factory. /// The HRESULT for the operation. [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate int FactoryDelegate(IUnknown** effectImpl); + public delegate int FactoryDelegate(IUnknown** effectImpl); /// - /// A generic pixel shader implementation. + /// A base type with global values for pixel shader effects. /// - /// The type of shader. - public sealed class For - where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor + public abstract class Globals { /// - /// The wrapper for the shader factory. + /// Gets the wrapper for the shader factory. /// private readonly FactoryDelegate effectFactory; /// - /// The for the shader. - /// - /// - /// This field could have used 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. - /// - private readonly Guid shaderId; - - /// - /// The size of the constant buffer for the shader. - /// - private readonly int constantBufferSize; - - /// - /// The number of inputs for the shader. - /// - private readonly int inputCount; - - /// - /// The buffer with the types of inputs for the shader. - /// - private readonly D2D1PixelShaderInputType* inputTypes; - - /// - /// The number of available input descriptions. - /// - private readonly int inputDescriptionCount; - - /// - /// The buffer with the available input descriptions for the shader. - /// - private readonly D2D1InputDescription* inputDescriptions; - - /// - /// The pixel options for the shader. - /// - private readonly D2D1PixelOptions pixelOptions; - - /// - /// The shader bytecode. - /// - private readonly byte* bytecode; - - /// - /// The size of . - /// - private readonly int bytecodeSize; - - /// - /// The buffer precision for the resulting output buffer. - /// - private readonly D2D1BufferPrecision bufferPrecision; - - /// - /// The channel depth for the resulting output buffer. - /// - private readonly D2D1ChannelDepth channelDepth; - - /// - /// The number of available resource texture descriptions. - /// - private readonly int resourceTextureDescriptionCount; - - /// - /// The buffer with the available resource texture descriptions for the shader. - /// - private readonly D2D1ResourceTextureDescription* resourceTextureDescriptions; - - /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The wrapper for the shader factory. - /// The for the shader. - /// The size of the constant buffer for the shader. - /// The number of inputs for the shader. - /// The buffer with the types of inputs for the shader. - /// The number of available input descriptions. - /// The buffer with the available input descriptions for the shader. - /// The pixel options for the shader. - /// The shader bytecode. - /// The size of . - /// The buffer precision for the resulting output buffer. - /// The channel depth for the resulting output buffer. - /// The number of available resource texture descriptions. - /// The buffer with the available resource texture descriptions for the shader. - 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) + protected Globals(FactoryDelegate effectFactory) { 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; } - /// - /// Gets the shared instance. - /// - public static For Instance { get; } = CreateInstance(); + /// + public abstract ref readonly Guid EffectId { get; } - /// - /// Creates a new instance. - /// - /// The initialized instance. - private static For CreateInstance() - { - // Load all shader properties - Guid shaderId = D2D1PixelShaderEffect.GetEffectId(); - int constantBufferSize = D2D1PixelShader.GetConstantBufferSize(); - D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision(); - D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth(); - D2D1PixelOptions pixelOptions = D2D1PixelShader.GetPixelOptions(); + /// + public abstract int ConstantBufferSize { get; } - // Prepare the inputs info - int inputCount = D2D1PixelShader.GetInputCount(); - D2D1PixelShaderInputType* inputTypes = (D2D1PixelShaderInputType*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1PixelShaderInputType) * inputCount); + /// + public abstract int InputCount { get; } - D2D1PixelShader.GetInputTypes().Span.CopyTo(new Span(inputTypes, inputCount)); + /// + public abstract int ResourceTextureCount { get; } - // Prepare the input descriptions - ReadOnlyMemory inputDescriptionsInfo = D2D1PixelShader.GetInputDescriptions(); - int inputDescriptionCount = inputDescriptionsInfo.Length; - D2D1InputDescription* inputDescriptions = (D2D1InputDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1InputDescription) * inputDescriptionCount); + /// + public abstract ReadOnlyMemory InputTypes { get; } - inputDescriptionsInfo.Span.CopyTo(new Span(inputDescriptions, inputDescriptionCount)); + /// + public abstract ReadOnlyMemory InputDescriptions { get; } - // Prepare the resource texture descriptions - ReadOnlyMemory resourceTextureDescriptionsInfo = D2D1PixelShader.GetResourceTextureDescriptions(); - int resourceTextureDescriptionCount = resourceTextureDescriptionsInfo.Length; - D2D1ResourceTextureDescription* resourceTextureDescriptions = (D2D1ResourceTextureDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1ResourceTextureDescription) * resourceTextureDescriptionCount); + /// + public abstract ReadOnlyMemory ResourceTextureDescriptions { get; } - resourceTextureDescriptionsInfo.Span.CopyTo(new Span(resourceTextureDescriptions, resourceTextureDescriptionCount)); + /// + public abstract D2D1PixelOptions PixelOptions { get; } - // Copy the bytecode to the target buffer - ReadOnlyMemory bytecodeInfo = D2D1PixelShader.LoadBytecode(); - int bytecodeSize = bytecodeInfo.Length; - byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), bytecodeSize); + /// + public abstract D2D1BufferPrecision BufferPrecision { get; } - bytecodeInfo.Span.CopyTo(new Span(bytecode, bytecodeSize)); + /// + public abstract D2D1ChannelDepth ChannelDepth { get; } - // Initialize the shared instance with the computed state - return new( - CreateEffect, - shaderId, - constantBufferSize, - inputCount, - inputTypes, - inputDescriptionCount, - inputDescriptions, - pixelOptions, - bytecode, - bytecodeSize, - bufferPrecision, - channelDepth, - resourceTextureDescriptionCount, - resourceTextureDescriptions); - } - - /// - /// Gets a reference to the id of the effect. - /// - public ref readonly Guid Id - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => ref this.shaderId; - } + /// + public abstract ReadOnlyMemory HlslBytecode { get; } /// /// Gets the factory for the current effect. @@ -242,32 +88,83 @@ internal unsafe partial struct PixelShaderEffect get => (void*)Marshal.GetFunctionPointerForDelegate(this.effectFactory); #endif } + } + + /// + /// A generic pixel shader implementation. + /// + /// The type of shader. + public sealed class Globals : Globals + where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor + { + /// + /// The HLSL bytecode (either precompiled, or the currently available one after compilation). + /// + private ReadOnlyMemory hlslBytecode; /// - /// Gets the number of inputs for the effect. + /// Creates a new instance for shaders of type . /// - public int InputCount => this.inputCount; + private Globals() + : base(CreateEffect) + { + } + + /// + /// Gets the shared instance to use. + /// + public static Globals Instance { get; } = new(); + + /// + public override ref readonly Guid EffectId => ref D2D1PixelShaderEffect.GetEffectId(); + + /// + public override int ConstantBufferSize => D2D1PixelShader.GetConstantBufferSize(); + + /// + public override int InputCount => D2D1PixelShader.GetInputCount(); + + /// + public override int ResourceTextureCount => D2D1PixelShader.GetResourceTextureCount(); + + /// + public override ReadOnlyMemory InputTypes => D2D1PixelShader.GetInputTypes(); + + /// + public override ReadOnlyMemory InputDescriptions => D2D1PixelShader.GetInputDescriptions(); + + /// + public override ReadOnlyMemory ResourceTextureDescriptions => D2D1PixelShader.GetResourceTextureDescriptions(); + + /// + public override D2D1PixelOptions PixelOptions => D2D1PixelShader.GetPixelOptions(); + + /// + public override D2D1BufferPrecision BufferPrecision => D2D1PixelShader.GetOutputBufferPrecision(); + + /// + public override D2D1ChannelDepth ChannelDepth => D2D1PixelShader.GetOutputBufferChannelDepth(); + + /// + public override ReadOnlyMemory HlslBytecode + { + get + { + // Fast path if we already have some bytecode (either precompiled, or already compiled) + if (this.hlslBytecode is ReadOnlyMemory { Length: > 0 } hlslBytecode) + { + return hlslBytecode; + } + + // If not, lazily compile the bytecode when requested + return this.hlslBytecode = D2D1PixelShader.LoadBytecode(); + } + } /// private static int CreateEffect(IUnknown** effectImpl) { - For 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); + return PixelShaderEffect.Factory(Instance, effectImpl); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs index 21ebdd53..6dbb2ec5 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -110,7 +110,7 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - return (uint)@this->inputCount; + return (uint)@this->GetGlobals().InputCount; } /// @@ -119,7 +119,7 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - if (inputRectsCount != @this->inputCount) + if (inputRectsCount != @this->GetGlobals().InputCount) { return E.E_INVALIDARG; } @@ -136,6 +136,8 @@ partial struct PixelShaderEffect } else { + ReadOnlySpan 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 @@ -143,7 +145,7 @@ partial struct PixelShaderEffect // will handle clipping the inputs to the actual output rect area, if needed. for (uint i = 0; i < inputRectsCount; i++) { - switch (@this->inputTypes[i]) + switch (inputTypes[(int)i]) { case D2D1PixelShaderInputType.Simple: inputRects[i] = *outputRect; @@ -166,7 +168,7 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - if (inputRectCount != @this->inputCount) + if (inputRectCount != @this->GetGlobals().InputCount) { return E.E_INVALIDARG; } @@ -179,7 +181,7 @@ partial struct PixelShaderEffect HRESULT hresult = D2D1DrawInfoUpdateContextImpl.Factory( drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(), constantBuffer: @this->constantBuffer, - constantBufferSize: @this->constantBufferSize, + constantBufferSize: @this->GetGlobals().ConstantBufferSize, d2D1DrawInfo: @this->d2D1DrawInfo); if (!Windows.SUCCEEDED(hresult)) @@ -215,6 +217,8 @@ partial struct PixelShaderEffect } else { + ReadOnlySpan 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 @@ -224,7 +228,7 @@ partial struct PixelShaderEffect for (uint i = 0; i < inputRectCount; i++) { - if (@this->inputTypes[i] == D2D1PixelShaderInputType.Simple) + if (inputTypes[(int)i] == D2D1PixelShaderInputType.Simple) { if (isUnionOfSimpleRectsEmpty) { @@ -259,7 +263,7 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - if (inputIndex >= (uint)@this->inputCount) + if (inputIndex >= (uint)@this->GetGlobals().InputCount) { return E.E_INVALIDARG; } @@ -278,7 +282,7 @@ partial struct PixelShaderEffect { // 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]) + switch (@this->GetGlobals().InputTypes.Span[(int)inputIndex]) { case D2D1PixelShaderInputType.Simple: *invalidOutputRect = invalidInputRect; @@ -311,8 +315,11 @@ partial struct PixelShaderEffect @this->d2D1DrawInfo = drawInfo; + Guid shaderId = @this->GetGlobals().EffectId; + D2D1PixelOptions pixelOptions = @this->GetGlobals().PixelOptions; + // Set the pixel shader for the effect - HRESULT hresult = drawInfo->SetPixelShader(&@this->shaderId, (D2D1_PIXEL_OPTIONS)@this->pixelOptions); + HRESULT hresult = drawInfo->SetPixelShader(&shaderId, (D2D1_PIXEL_OPTIONS)pixelOptions); if (hresult != S.S_OK) { @@ -320,32 +327,30 @@ partial struct PixelShaderEffect } // If any input descriptions are present, set them - if (@this->inputDescriptionCount > 0) + foreach (ref readonly D2D1InputDescription inputDescription in @this->GetGlobals().InputDescriptions.Span) { - for (int i = 0; i < @this->inputDescriptionCount; 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) { - 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; - } + return hresult; } } + D2D1BufferPrecision bufferPrecision = @this->GetGlobals().BufferPrecision; + D2D1ChannelDepth channelDepth = @this->GetGlobals().ChannelDepth; + // If a custom buffer precision or channel depth is requested, set it - if (@this->bufferPrecision != D2D1BufferPrecision.Unknown || - @this->channelDepth != D2D1ChannelDepth.Default) + if (bufferPrecision != D2D1BufferPrecision.Unknown || + channelDepth != D2D1ChannelDepth.Default) { hresult = drawInfo->SetOutputBuffer( - (D2D1_BUFFER_PRECISION)@this->bufferPrecision, - (D2D1_CHANNEL_DEPTH)@this->channelDepth); + (D2D1_BUFFER_PRECISION)bufferPrecision, + (D2D1_CHANNEL_DEPTH)channelDepth); if (hresult != S.S_OK) { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs index 2450925e..6c70ad3d 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs @@ -86,17 +86,24 @@ 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); + ReadOnlySpan bytecode = @this->GetGlobals().HlslBytecode.Span; + int hresult; - // 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) + fixed (Guid* pShaderId = &@this->GetGlobals().EffectId) + fixed (byte* pBytecode = bytecode) { - hresult = D2DERR.D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES; + 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; + } } // If loading the bytecode succeeded, set the transform node @@ -130,7 +137,7 @@ internal unsafe partial struct PixelShaderEffect int hresult = S.S_OK; // Validate the constant buffer - if (@this->constantBufferSize > 0 && + if (@this->GetGlobals().ConstantBufferSize > 0 && @this->constantBuffer is null) { return E.E_NOT_VALID_STATE; @@ -141,12 +148,14 @@ internal unsafe partial struct PixelShaderEffect { hresult = @this->d2D1DrawInfo->SetPixelShaderConstantBuffer( buffer: @this->constantBuffer, - bufferCount: (uint)@this->constantBufferSize); + bufferCount: (uint)@this->GetGlobals().ConstantBufferSize); } if (Windows.SUCCEEDED(hresult)) { - for (int i = 0; i < @this->resourceTextureDescriptionCount; i++) + ReadOnlySpan resourceTextureDescriptions = @this->GetGlobals().ResourceTextureDescriptions.Span; + + for (int i = 0; i < resourceTextureDescriptions.Length; i++) { using ComPtr resourceTextureManager = @this->resourceTextureManagerBuffer[i]; @@ -180,7 +189,7 @@ internal unsafe partial struct PixelShaderEffect 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( diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs index 3eff1fa7..9abc2a11 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs @@ -120,7 +120,7 @@ unsafe partial struct PixelShaderEffect dataSize == 0 && actualSize is not null) { - *actualSize = (uint)@this->constantBufferSize; + *actualSize = (uint)@this->GetGlobals().ConstantBufferSize; return S.S_FALSE; } @@ -130,7 +130,7 @@ unsafe partial struct PixelShaderEffect return E.E_POINTER; } - if (dataSize < @this->constantBufferSize) + if (dataSize < @this->GetGlobals().ConstantBufferSize) { return E.E_NOT_SUFFICIENT_BUFFER; } @@ -142,11 +142,11 @@ unsafe partial struct PixelShaderEffect uint writtenBytes = 0; - if (@this->constantBufferSize > 0) + if (@this->GetGlobals().ConstantBufferSize > 0) { - Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, @this->constantBufferSize); + Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, @this->GetGlobals().ConstantBufferSize); - writtenBytes = (uint)@this->constantBufferSize; + writtenBytes = (uint)@this->GetGlobals().ConstantBufferSize; } if (actualSize is not null) @@ -168,7 +168,7 @@ unsafe partial struct PixelShaderEffect return E.E_POINTER; } - if (dataSize != (uint)@this->constantBufferSize) + if (dataSize != (uint)@this->GetGlobals().ConstantBufferSize) { return E.E_INVALIDARG; } @@ -284,7 +284,7 @@ unsafe partial struct PixelShaderEffect /// The for the operation. private int GetResourceTextureManagerAtIndex(int index, byte* data, uint dataSize, uint* actualSize) { - if (index >= this.resourceTextureDescriptionCount) + if (index >= GetGlobals().ResourceTextureCount) { return E.E_INVALIDARG; } @@ -325,7 +325,7 @@ unsafe partial struct PixelShaderEffect /// The for the operation. private int SetResourceTextureManagerAtIndex(int index, byte* data, uint dataSize) { - if (index >= this.resourceTextureDescriptionCount) + if (index >= GetGlobals().ResourceTextureCount) { return E.E_INVALIDARG; } @@ -371,7 +371,7 @@ unsafe partial struct PixelShaderEffect // Initialize the resource texture manager, if an effect context is available if (this.d2D1EffectContext is not null) { - uint dimensions = (uint)this.resourceTextureDescriptions[index].Dimensions; + uint dimensions = (uint)GetGlobals().ResourceTextureDescriptions.Span[index].Dimensions; result = resourceTextureManagerInternal.Get()->Initialize(this.d2D1EffectContext, &dimensions); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index 3106e5df..32d6ec72 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -106,86 +106,15 @@ internal unsafe partial struct PixelShaderEffect private volatile int referenceCount; /// - /// The for the shader. + /// The for the instance in use. /// - private Guid shaderId; + private GCHandle globalsHandle; /// /// The constant buffer data, if set. /// private byte* constantBuffer; - /// - /// The size of . - /// - private int constantBufferSize; - - /// - /// The number of inputs for the shader. - /// - private int inputCount; - - /// - /// The buffer with the types of inputs for the shader. - /// - /// - /// This buffer is shared among effect instances, so it should not be released. It is - /// owned by , which will release it when the target type is unloaded. - /// - private D2D1PixelShaderInputType* inputTypes; - - /// - /// The number of available input descriptions. - /// - private int inputDescriptionCount; - - /// - /// The buffer with the available input descriptions for the shader. - /// - /// - /// This buffer is also shared among effect instances, so it should not be released. It is - /// owned by , which will release it when the target type is unloaded. - /// - private D2D1InputDescription* inputDescriptions; - - /// - /// The pixel options for the shader. - /// - private D2D1PixelOptions pixelOptions; - - /// - /// The shader bytecode. - /// - private byte* bytecode; - - /// - /// The size of . - /// - private int bytecodeSize; - - /// - /// The buffer precision for the resulting output buffer. - /// - private D2D1BufferPrecision bufferPrecision; - - /// - /// The channel depth for the resulting output buffer. - /// - private D2D1ChannelDepth channelDepth; - - /// - /// The number of available resource texture descriptions. - /// - private int resourceTextureDescriptionCount; - - /// - /// The buffer with the available resource texture descriptions for the shader. - /// - /// - /// This buffer is also shared among effect instances, like . - /// - private D2D1ResourceTextureDescription* resourceTextureDescriptions; - /// /// The instance to use, if any. /// @@ -209,45 +138,33 @@ internal unsafe partial struct PixelShaderEffect /// /// The factory method for . /// - /// The for the shader. - /// The size of the constant buffer for the shader. - /// The number of inputs for the shader. - /// The buffer with the types of inputs for the shader. - /// The number of available input descriptions. - /// The buffer with the available input descriptions for the shader. - /// The pixel options for the shader. - /// The shader bytecode. - /// The size of . - /// The buffer precision for the resulting output buffer. - /// The channel depth for the resulting output buffer. - /// The number of available resource texture descriptions. - /// The buffer with the available resource texture descriptions for the shader. + /// The instance to use. /// The resulting effect instance. - /// This always returns 0. - 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) + /// The for the operation. + 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); } - catch (OutOfMemoryException) + catch (Exception) { + // Free the effect, if we have one + if (@this is not null) + { + NativeMemory.Free(@this); + } + + // Free the handle, if we have one + if (globalsHandle.IsAllocated) + { + globalsHandle.Free(); + } + *effectImpl = null; return E.E_OUTOFMEMORY; @@ -258,20 +175,8 @@ internal unsafe partial struct PixelShaderEffect @this->lpVtblForID2D1EffectImpl = VtblForID2D1EffectImpl; @this->lpVtblForID2D1DrawTransform = VtblForID2D1DrawTransform; @this->referenceCount = 1; - @this->shaderId = shaderId; + @this->globalsHandle = globalsHandle; @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; @@ -331,6 +236,14 @@ internal unsafe partial struct PixelShaderEffect if (referenceCount == 0) { + // Retrieve the number of resource textures before freeing the globals handle + int resourceTextureDescriptionCount = GetGlobals().ResourceTextureCount; + + if (this.globalsHandle.IsAllocated) + { + this.globalsHandle.Free(); + } + if (this.constantBuffer is not null) { NativeMemory.Free(this.constantBuffer); @@ -352,7 +265,7 @@ internal unsafe partial struct PixelShaderEffect } // 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++) + for (int i = 0; i < resourceTextureDescriptionCount; i++) { ID2D1ResourceTextureManager* resourceTextureManager = this.resourceTextureManagerBuffer[i]; @@ -367,4 +280,14 @@ internal unsafe partial struct PixelShaderEffect return referenceCount; } + + /// + /// Gets the instance for the current effect. + /// + /// The instance for the current effect. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Globals GetGlobals() + { + return Unsafe.As(this.globalsHandle.Target!); + } } \ No newline at end of file From 38f1d37d172972b6a8c3381c8b61ac5b206ce6b2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 5 Oct 2023 10:36:11 +0200 Subject: [PATCH 02/11] Rename file to match new Globals types --- ...ixelShaderEffect.For{T}.cs => PixelShaderEffect.Globals{T}.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/ComputeSharp.D2D1/Shaders/Interop/Effects/{PixelShaderEffect.For{T}.cs => PixelShaderEffect.Globals{T}.cs} (100%) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Globals{T}.cs similarity index 100% rename from src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs rename to src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Globals{T}.cs From 3b31b9abe2fd89875f64d09ff85b86d7136a5913 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 6 Oct 2023 10:59:05 +0200 Subject: [PATCH 03/11] Remove unnecessary NativeMemory.Free branches --- .../Interop/Effects/PixelShaderEffect.cs | 10 ++----- .../D2D1ResourceTextureManagerImpl.cs | 29 ++++--------------- 2 files changed, 7 insertions(+), 32 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index 32d6ec72..49f7428b 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -154,10 +154,7 @@ internal unsafe partial struct PixelShaderEffect catch (Exception) { // Free the effect, if we have one - if (@this is not null) - { - NativeMemory.Free(@this); - } + NativeMemory.Free(@this); // Free the handle, if we have one if (globalsHandle.IsAllocated) @@ -244,10 +241,7 @@ internal unsafe partial struct PixelShaderEffect this.globalsHandle.Free(); } - if (this.constantBuffer is not null) - { - NativeMemory.Free(this.constantBuffer); - } + NativeMemory.Free(this.constantBuffer); if (this.d2D1TransformMapper is not null) { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs index 575fdcc6..e501fddb 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs @@ -263,30 +263,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(); From 4ec0b1e43e1b167174e93138f541cff72d51e6cb Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 6 Oct 2023 11:11:46 +0200 Subject: [PATCH 04/11] Add ComPtr.Release to simplify native objects --- ...lShaderEffect.ID2D1DrawTransformMethods.cs | 5 +--- ...ixelShaderEffect.ID2D1EffectImplMethods.cs | 5 +--- .../Effects/PixelShaderEffect.Properties.cs | 10 ++------ .../Interop/Effects/PixelShaderEffect.cs | 24 ++++--------------- .../D2D1ResourceTextureManagerImpl.cs | 5 +--- src/TerraFX.Interop.Windows/ComPtr`1.cs | 13 ++++++++++ 6 files changed, 22 insertions(+), 40 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs index 6dbb2ec5..893d04a4 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -305,10 +305,7 @@ partial struct PixelShaderEffect @this = (PixelShaderEffect*)&((void**)@this)[-1]; // Free the previous ID2D1DrawInfo object, if present - if (@this->d2D1DrawInfo is not null) - { - _ = @this->d2D1DrawInfo->Release(); - } + ComPtr.Release(@this->d2D1DrawInfo); // Store the new ID2D1DrawInfo object _ = drawInfo->AddRef(); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs index 6c70ad3d..5f1d26bf 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs @@ -116,10 +116,7 @@ internal unsafe partial struct PixelShaderEffect if (Windows.SUCCEEDED(hresult)) { // Free the previous ID2D1EffectContext object, if present - if (@this->d2D1EffectContext is not null) - { - _ = @this->d2D1EffectContext->Release(); - } + ComPtr.Release(@this->d2D1EffectContext); // Store the new ID2D1EffectContext object _ = effectContext->AddRef(); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs index 9abc2a11..25dc7e52 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs @@ -263,10 +263,7 @@ unsafe partial struct PixelShaderEffect } // If there's already an existing manager, release it - if (@this->d2D1TransformMapper is not null) - { - _ = ((IUnknown*)@this->d2D1TransformMapper)->Release(); - } + ComPtr.Release(@this->d2D1TransformMapper); // Store the transform mapper manager into the effect @this->d2D1TransformMapper = transformMapper.Detach(); @@ -389,10 +386,7 @@ unsafe partial struct PixelShaderEffect ref ID2D1ResourceTextureManager* currentResourceTextureManager = ref this.resourceTextureManagerBuffer[index]; // If there's already an existing manager at this index, release it - if (currentResourceTextureManager is not null) - { - _ = ((IUnknown*)currentResourceTextureManager)->Release(); - } + ComPtr.Release(currentResourceTextureManager); // Store the resource texture manager into the buffer currentResourceTextureManager = resourceTextureManager.Detach(); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index 49f7428b..8aa37e86 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -243,30 +243,14 @@ internal unsafe partial struct PixelShaderEffect NativeMemory.Free(this.constantBuffer); - if (this.d2D1TransformMapper is not null) - { - _ = ((IUnknown*)this.d2D1TransformMapper)->Release(); - } - - if (this.d2D1DrawInfo is not null) - { - _ = this.d2D1DrawInfo->Release(); - } - - if (this.d2D1EffectContext is not null) - { - _ = this.d2D1EffectContext->Release(); - } + ComPtr.Release(this.d2D1TransformMapper); + ComPtr.Release(this.d2D1DrawInfo); + ComPtr.Release(this.d2D1EffectContext); // 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 < resourceTextureDescriptionCount; i++) { - ID2D1ResourceTextureManager* resourceTextureManager = this.resourceTextureManagerBuffer[i]; - - if (resourceTextureManager is not null) - { - _ = ((IUnknown*)resourceTextureManager)->Release(); - } + ComPtr.Release(this.resourceTextureManagerBuffer[i]); } NativeMemory.Free(Unsafe.AsPointer(ref this)); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs index e501fddb..a5fe07c4 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs @@ -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.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 diff --git a/src/TerraFX.Interop.Windows/ComPtr`1.cs b/src/TerraFX.Interop.Windows/ComPtr`1.cs index dcfa9e1f..abb74bcc 100644 --- a/src/TerraFX.Interop.Windows/ComPtr`1.cs +++ b/src/TerraFX.Interop.Windows/ComPtr`1.cs @@ -38,6 +38,19 @@ internal unsafe struct ComPtr : IDisposable InternalAddRef(); } + /// + /// Releases a target COM object, if it's not . + /// + /// The COM object to potentially release. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Release(T* other) + { + if (other is not null) + { + _ = ((IUnknown*)other)->Release(); + } + } + /// Converts a raw pointer to a new instance and increments the ref count. /// The raw pointer to wrap. [MethodImpl(MethodImplOptions.AggressiveInlining)] From 6c75fc32c6e4204a43f7c415a3483b4491f69229 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 6 Oct 2023 11:14:24 +0200 Subject: [PATCH 05/11] Remove some leftover extensions --- .../Extensions/Interop/ComPtrExtensions.cs | 46 ------------------- 1 file changed, 46 deletions(-) diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs index 0b14b7fe..7909fd04 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/ComPtrExtensions.cs @@ -8,52 +8,6 @@ namespace ComputeSharp.Core.Extensions; /// internal static class ComPtrExtensions { -#if NET6_0_OR_GREATER - /// - /// Invokes on the wrapped object for an input value. - /// - /// The type of the current instance. - /// The input instance to increment the reference count for. - /// A instance of type . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe uint AddRef(this ComPtr ptr) - where T : unmanaged, IUnknown.Interface - { - if (ptr.Get() is not null) - { - return ptr.Get()->AddRef(); - } - - return 0; - } - - /// - /// Invokes on the wrapped object for an input value. - /// If the object has been deleted, it also resets . - /// - /// The type of the current instance. - /// The input instance to release. - /// A instance of type . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe uint Release(this ref ComPtr 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 - /// /// Reinterprets the current instance as one of type . /// From 011accfc264dfebde0dc89444da9b9f975840f38 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 7 Oct 2023 12:21:49 +0200 Subject: [PATCH 06/11] Add try/catch to pixel shader effect methods --- ...lShaderEffect.ID2D1DrawTransformMethods.cs | 381 ++++++++------- ...ixelShaderEffect.ID2D1EffectImplMethods.cs | 182 ++++---- .../Effects/PixelShaderEffect.Properties.cs | 432 ++++++++++-------- .../Interop/Effects/PixelShaderEffect.cs | 14 +- 4 files changed, 549 insertions(+), 460 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs index 893d04a4..a87af065 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -110,7 +110,16 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - return (uint)@this->GetGlobals().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; + } } /// @@ -119,47 +128,54 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - if (inputRectsCount != @this->GetGlobals().InputCount) + try { - return E.E_INVALIDARG; - } - - 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 (inputRectsCount != @this->GetGlobals().InputCount) { - return hresult; + return E.E_INVALIDARG; } - } - else - { - ReadOnlySpan 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++) + if (@this->d2D1TransformMapper is not null) { - switch (inputTypes[(int)i]) + // Forward to the current ID2D1TransformMapper instance + HRESULT hresult = @this->d2D1TransformMapper->MapOutputRectToInputRects(outputRect, inputRects, inputRectsCount); + + if (!Windows.SUCCEEDED(hresult)) { - case D2D1PixelShaderInputType.Simple: - inputRects[i] = *outputRect; - break; - case D2D1PixelShaderInputType.Complex: - inputRects[i].MakeD2D1Infinite(); - break; - default: - return E.E_FAIL; + return hresult; } } - } + else + { + ReadOnlySpan inputTypes = @this->GetGlobals().InputTypes.Span; - return S.S_OK; + // 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++) + { + 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; + } + catch (Exception e) + { + return Marshal.GetHRForException(e); + } } /// @@ -168,93 +184,100 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - if (inputRectCount != @this->GetGlobals().InputCount) + try { - return E.E_INVALIDARG; - } - - if (@this->d2D1TransformMapper is not null) - { - using ComPtr d2D1DrawInfoUpdateContext = default; - - // Create an ID2D1DrawInfoUpdateContext instance - HRESULT hresult = D2D1DrawInfoUpdateContextImpl.Factory( - drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(), - constantBuffer: @this->constantBuffer, - constantBufferSize: @this->GetGlobals().ConstantBufferSize, - d2D1DrawInfo: @this->d2D1DrawInfo); - - if (!Windows.SUCCEEDED(hresult)) + if (inputRectCount != @this->GetGlobals().InputCount) { - return hresult; + return E.E_INVALIDARG; } - // 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)) + if (@this->d2D1TransformMapper is not null) { - 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(); + using ComPtr d2D1DrawInfoUpdateContext = default; - *outputOpaqueSubRect = default; - } - else - { - ReadOnlySpan inputTypes = @this->GetGlobals().InputTypes.Span; + // Create an ID2D1DrawInfoUpdateContext instance + HRESULT hresult = D2D1DrawInfoUpdateContextImpl.Factory( + drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(), + constantBuffer: @this->constantBuffer, + constantBufferSize: @this->GetGlobals().ConstantBufferSize, + d2D1DrawInfo: @this->d2D1DrawInfo); - // 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 (!Windows.SUCCEEDED(hresult)) { - if (isUnionOfSimpleRectsEmpty) - { - unionOfSimpleRects = inputRects[i]; - isUnionOfSimpleRectsEmpty = false; - } - else - { - unionOfSimpleRects = unionOfSimpleRects.Union(inputRects[i]); - } + return hresult; + } + + // 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; } } - - 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 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; } /// @@ -263,39 +286,46 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - if (inputIndex >= (uint)@this->GetGlobals().InputCount) + try { - return E.E_INVALIDARG; - } - - 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 (inputIndex >= (uint)@this->GetGlobals().InputCount) { - return hresult; + return E.E_INVALIDARG; } - } - 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->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; + if (@this->d2D1TransformMapper is not null) + { + // Forward to the current ID2D1TransformMapper instance + HRESULT hresult = @this->d2D1TransformMapper->MapInvalidRect(inputIndex, invalidInputRect, invalidOutputRect); + + if (!Windows.SUCCEEDED(hresult)) + { + return hresult; + } + } + 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->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; + } + catch (Exception e) + { + return Marshal.GetHRForException(e); + } } /// @@ -304,58 +334,65 @@ partial struct PixelShaderEffect { @this = (PixelShaderEffect*)&((void**)@this)[-1]; - // Free the previous ID2D1DrawInfo object, if present - ComPtr.Release(@this->d2D1DrawInfo); - - // Store the new ID2D1DrawInfo object - _ = drawInfo->AddRef(); - - @this->d2D1DrawInfo = drawInfo; - - Guid shaderId = @this->GetGlobals().EffectId; - D2D1PixelOptions pixelOptions = @this->GetGlobals().PixelOptions; - - // Set the pixel shader for the effect - HRESULT hresult = drawInfo->SetPixelShader(&shaderId, (D2D1_PIXEL_OPTIONS)pixelOptions); - - if (hresult != S.S_OK) + try { - return hresult; - } + // Free the previous ID2D1DrawInfo object, if present + ComPtr.Release(@this->d2D1DrawInfo); - // If any input descriptions are present, set them - foreach (ref readonly D2D1InputDescription inputDescription in @this->GetGlobals().InputDescriptions.Span) - { - D2D1_INPUT_DESCRIPTION d2D1InputDescription; - d2D1InputDescription.filter = (D2D1_FILTER)inputDescription.Filter; - d2D1InputDescription.levelOfDetailCount = (uint)inputDescription.LevelOfDetailCount; + // Store the new ID2D1DrawInfo object + _ = drawInfo->AddRef(); - hresult = drawInfo->SetInputDescription((uint)inputDescription.Index, d2D1InputDescription); + @this->d2D1DrawInfo = drawInfo; + + Guid shaderId = @this->GetGlobals().EffectId; + D2D1PixelOptions pixelOptions = @this->GetGlobals().PixelOptions; + + // Set the pixel shader for the effect + HRESULT hresult = drawInfo->SetPixelShader(&shaderId, (D2D1_PIXEL_OPTIONS)pixelOptions); if (hresult != S.S_OK) { return hresult; } - } - D2D1BufferPrecision bufferPrecision = @this->GetGlobals().BufferPrecision; - D2D1ChannelDepth channelDepth = @this->GetGlobals().ChannelDepth; - - // If a custom buffer precision or channel depth is requested, set it - if (bufferPrecision != D2D1BufferPrecision.Unknown || - channelDepth != D2D1ChannelDepth.Default) - { - hresult = drawInfo->SetOutputBuffer( - (D2D1_BUFFER_PRECISION)bufferPrecision, - (D2D1_CHANNEL_DEPTH)channelDepth); - - if (hresult != S.S_OK) + // If any input descriptions are present, set them + foreach (ref readonly D2D1InputDescription inputDescription in @this->GetGlobals().InputDescriptions.Span) { - return hresult; - } - } + D2D1_INPUT_DESCRIPTION d2D1InputDescription; + d2D1InputDescription.filter = (D2D1_FILTER)inputDescription.Filter; + d2D1InputDescription.levelOfDetailCount = (uint)inputDescription.LevelOfDetailCount; - return S.S_OK; + hresult = drawInfo->SetInputDescription((uint)inputDescription.Index, d2D1InputDescription); + + if (hresult != S.S_OK) + { + return hresult; + } + } + + D2D1BufferPrecision bufferPrecision = @this->GetGlobals().BufferPrecision; + D2D1ChannelDepth channelDepth = @this->GetGlobals().ChannelDepth; + + // If a custom buffer precision or channel depth is requested, set it + if (bufferPrecision != D2D1BufferPrecision.Unknown || + channelDepth != D2D1ChannelDepth.Default) + { + hresult = drawInfo->SetOutputBuffer( + (D2D1_BUFFER_PRECISION)bufferPrecision, + (D2D1_CHANNEL_DEPTH)channelDepth); + + if (hresult != S.S_OK) + { + return hresult; + } + } + + return S.S_OK; + } + catch (Exception e) + { + return Marshal.GetHRForException(e); + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs index 5f1d26bf..fea6cd51 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs @@ -86,121 +86,135 @@ internal unsafe partial struct PixelShaderEffect [UnmanagedCallersOnly] public static int Initialize(PixelShaderEffect* @this, ID2D1EffectContext* effectContext, ID2D1TransformGraph* transformGraph) { - ReadOnlySpan bytecode = @this->GetGlobals().HlslBytecode.Span; - int hresult; - - fixed (Guid* pShaderId = &@this->GetGlobals().EffectId) - fixed (byte* pBytecode = bytecode) + try { - hresult = effectContext->LoadPixelShader( - shaderId: pShaderId, - shaderBuffer: pBytecode, - shaderBufferCount: (uint)bytecode.Length); + ReadOnlySpan bytecode = @this->GetGlobals().HlslBytecode.Span; + int hresult; - // 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) + fixed (Guid* pShaderId = &@this->GetGlobals().EffectId) + fixed (byte* pBytecode = bytecode) { - hresult = D2DERR.D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES; + 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; + } } - } - // If loading the bytecode succeeded, set the transform node - if (Windows.SUCCEEDED(hresult)) + // 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 + ComPtr.Release(@this->d2D1EffectContext); + + // Store the new ID2D1EffectContext object + _ = effectContext->AddRef(); + + @this->d2D1EffectContext = effectContext; + } + + return hresult; + } + catch (Exception e) { - hresult = transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform); + return Marshal.GetHRForException(e); } - - // If the transform node was set, also store the effect context - if (Windows.SUCCEEDED(hresult)) - { - // Free the previous ID2D1EffectContext object, if present - ComPtr.Release(@this->d2D1EffectContext); - - // Store the new ID2D1EffectContext object - _ = effectContext->AddRef(); - - @this->d2D1EffectContext = effectContext; - } - - return hresult; } /// [UnmanagedCallersOnly] public static int PrepareForRender(PixelShaderEffect* @this, D2D1_CHANGE_TYPE changeType) { - int hresult = S.S_OK; - - // Validate the constant buffer - if (@this->GetGlobals().ConstantBufferSize > 0 && - @this->constantBuffer is null) + try { - return E.E_NOT_VALID_STATE; - } + int hresult = S.S_OK; - // First, set the constant buffer, if available - if (@this->constantBuffer is not null) - { - hresult = @this->d2D1DrawInfo->SetPixelShaderConstantBuffer( - buffer: @this->constantBuffer, - bufferCount: (uint)@this->GetGlobals().ConstantBufferSize); - } - - if (Windows.SUCCEEDED(hresult)) - { - ReadOnlySpan resourceTextureDescriptions = @this->GetGlobals().ResourceTextureDescriptions.Span; - - for (int i = 0; i < resourceTextureDescriptions.Length; i++) + // Validate the constant buffer + if (@this->GetGlobals().ConstantBufferSize > 0 && + @this->constantBuffer is null) { - using ComPtr resourceTextureManager = @this->resourceTextureManagerBuffer[i]; + return E.E_NOT_VALID_STATE; + } - // If the current resource texture manager is not set, we cannot render, as there's an unbound resource texture - if (resourceTextureManager.Get() is null) + // First, set the constant buffer, if available + if (@this->constantBuffer is not null) + { + hresult = @this->d2D1DrawInfo->SetPixelShaderConstantBuffer( + buffer: @this->constantBuffer, + bufferCount: (uint)@this->GetGlobals().ConstantBufferSize); + } + + if (Windows.SUCCEEDED(hresult)) + { + ReadOnlySpan resourceTextureDescriptions = @this->GetGlobals().ResourceTextureDescriptions.Span; + + for (int i = 0; i < resourceTextureDescriptions.Length; i++) { - hresult = E.E_NOT_VALID_STATE; + using ComPtr resourceTextureManager = @this->resourceTextureManagerBuffer[i]; - break; - } + // 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; - using ComPtr resourceTextureManagerInternal = default; + break; + } - // Get the ID2D1ResourceTextureManagerInternal object - hresult = resourceTextureManager.CopyTo(resourceTextureManagerInternal.GetAddressOf()); + using ComPtr resourceTextureManagerInternal = default; - // 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 + hresult = resourceTextureManager.CopyTo(resourceTextureManagerInternal.GetAddressOf()); - using ComPtr d2D1ResourceTexture = default; + // 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; + } - // Try to get the ID2D1ResourceTexture from the manager - hresult = resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf()); + using ComPtr d2D1ResourceTexture = default; - if (!Windows.SUCCEEDED(hresult)) - { - break; - } + // Try to get the ID2D1ResourceTexture from the manager + hresult = resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf()); - ref readonly D2D1ResourceTextureDescription resourceTextureDescription = ref resourceTextureDescriptions[i]; + if (!Windows.SUCCEEDED(hresult)) + { + break; + } - // Set the ID2D1ResourceTexture object to the current index in the ID2D1DrawInfo object in use - hresult = @this->d2D1DrawInfo->SetResourceTexture( - textureIndex: (uint)resourceTextureDescription.Index, - resourceTexture: d2D1ResourceTexture.Get()); + ref readonly D2D1ResourceTextureDescription resourceTextureDescription = ref resourceTextureDescriptions[i]; - if (!Windows.SUCCEEDED(hresult)) - { - break; + // Set the ID2D1ResourceTexture object to the current index in the ID2D1DrawInfo object in use + hresult = @this->d2D1DrawInfo->SetResourceTexture( + textureIndex: (uint)resourceTextureDescription.Index, + resourceTexture: d2D1ResourceTexture.Get()); + + if (!Windows.SUCCEEDED(hresult)) + { + break; + } } } - } - return hresult; + return hresult; + } + catch (Exception e) + { + return Marshal.GetHRForException(e); + } } /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs index 25dc7e52..862e24dd 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs @@ -115,46 +115,53 @@ 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->GetGlobals().ConstantBufferSize; + // This is a call likely from ID2D1Effect::GetValueSize, to query the property size + if (data is null && + dataSize == 0 && + actualSize is not null) + { + *actualSize = (uint)@this->GetGlobals().ConstantBufferSize; - return S.S_FALSE; + return S.S_FALSE; + } + + if (data is null) + { + return E.E_POINTER; + } + + 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->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; } /// @@ -163,31 +170,38 @@ unsafe partial struct PixelShaderEffect { PixelShaderEffect* @this = (PixelShaderEffect*)effect; - if (data is null) + try { - return E.E_POINTER; - } + if (data is null) + { + return E.E_POINTER; + } - if (dataSize != (uint)@this->GetGlobals().ConstantBufferSize) + if (dataSize != (uint)@this->GetGlobals().ConstantBufferSize) + { + return E.E_INVALIDARG; + } + + // 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; } /// @@ -196,36 +210,43 @@ unsafe partial struct PixelShaderEffect { PixelShaderEffect* @this = (PixelShaderEffect*)effect; - if (data is null) + try { - return E.E_POINTER; - } - - if (dataSize < sizeof(void*)) - { - return E.E_INVALIDARG; - } - - if (@this->d2D1TransformMapper is null) - { - *(void**)data = null; - } - else - { - HRESULT hresult = ((IUnknown*)@this->d2D1TransformMapper)->QueryInterface(Windows.__uuidof(), (void**)data); - - if (!Windows.SUCCEEDED(hresult)) + if (data is null) { - return hresult; + return E.E_POINTER; } - } - if (actualSize is not null) + 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(), (void**)data); + + if (!Windows.SUCCEEDED(hresult)) + { + return hresult; + } + } + + 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; } /// @@ -234,41 +255,48 @@ unsafe partial struct PixelShaderEffect { PixelShaderEffect* @this = (PixelShaderEffect*)effect; - if (data is null) + try { - return E.E_POINTER; + if (data is null) + { + return E.E_POINTER; + } + + void* value = *(void**)data; + + if (value is null) + { + return E.E_POINTER; + } + + if (dataSize != (uint)sizeof(void*)) + { + return E.E_INVALIDARG; + } + + using ComPtr unknown = (IUnknown*)value; + using ComPtr 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 + ComPtr.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 unknown = (IUnknown*)value; - using ComPtr 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 - ComPtr.Release(@this->d2D1TransformMapper); - - // Store the transform mapper manager into the effect - @this->d2D1TransformMapper = transformMapper.Detach(); - - return S.S_OK; } /// @@ -281,36 +309,43 @@ unsafe partial struct PixelShaderEffect /// The for the operation. private int GetResourceTextureManagerAtIndex(int index, byte* data, uint dataSize, uint* actualSize) { - if (index >= GetGlobals().ResourceTextureCount) + try { - return E.E_INVALIDARG; - } + if (index >= GetGlobals().ResourceTextureCount) + { + return E.E_INVALIDARG; + } - if (data is null) + if (data is null) + { + return E.E_POINTER; + } + + if (dataSize < sizeof(void*)) + { + return E.E_INVALIDARG; + } + + using ComPtr 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; + } + catch (Exception e) { - return E.E_POINTER; + return Marshal.GetHRForException(e); } - - if (dataSize < sizeof(void*)) - { - return E.E_INVALIDARG; - } - - using ComPtr 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; } /// @@ -322,75 +357,82 @@ unsafe partial struct PixelShaderEffect /// The for the operation. private int SetResourceTextureManagerAtIndex(int index, byte* data, uint dataSize) { - if (index >= GetGlobals().ResourceTextureCount) + try { - return E.E_INVALIDARG; - } + if (index >= GetGlobals().ResourceTextureCount) + { + return E.E_INVALIDARG; + } - if (data is null) - { - return E.E_POINTER; - } + if (data is null) + { + return E.E_POINTER; + } - void* value = *(void**)data; + void* value = *(void**)data; - if (value is null) - { - return E.E_POINTER; - } + if (value is null) + { + return E.E_POINTER; + } - if (dataSize != (uint)sizeof(void*)) - { - return E.E_INVALIDARG; - } + if (dataSize != (uint)sizeof(void*)) + { + return E.E_INVALIDARG; + } - using ComPtr unknown = (IUnknown*)value; - using ComPtr resourceTextureManager = default; + using ComPtr unknown = (IUnknown*)value; + using ComPtr resourceTextureManager = default; - // Check that the input object implements ID2D1ResourceTextureManager - int result = unknown.CopyTo(resourceTextureManager.GetAddressOf()); + // Check that the input object implements ID2D1ResourceTextureManager + int result = unknown.CopyTo(resourceTextureManager.GetAddressOf()); - if (result != S.S_OK) - { - return result; - } - - using ComPtr 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)GetGlobals().ResourceTextureDescriptions.Span[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)) + if (result != S.S_OK) { return result; } + + using ComPtr 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)GetGlobals().ResourceTextureDescriptions.Span[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)) + { + return result; + } + } + + ref ID2D1ResourceTextureManager* currentResourceTextureManager = ref this.resourceTextureManagerBuffer[index]; + + // If there's already an existing manager at this index, release it + ComPtr.Release(currentResourceTextureManager); + + // Store the resource texture manager into the buffer + currentResourceTextureManager = resourceTextureManager.Detach(); + + return S.S_OK; + } + catch (Exception e) + { + return Marshal.GetHRForException(e); } - - ref ID2D1ResourceTextureManager* currentResourceTextureManager = ref this.resourceTextureManagerBuffer[index]; - - // If there's already an existing manager at this index, release it - ComPtr.Release(currentResourceTextureManager); - - // Store the resource texture manager into the buffer - currentResourceTextureManager = resourceTextureManager.Detach(); - - return S.S_OK; } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index 8aa37e86..fb3a2acf 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -233,13 +233,7 @@ internal unsafe partial struct PixelShaderEffect if (referenceCount == 0) { - // Retrieve the number of resource textures before freeing the globals handle - int resourceTextureDescriptionCount = GetGlobals().ResourceTextureCount; - - if (this.globalsHandle.IsAllocated) - { - this.globalsHandle.Free(); - } + this.globalsHandle.Free(); NativeMemory.Free(this.constantBuffer); @@ -247,8 +241,10 @@ internal unsafe partial struct PixelShaderEffect ComPtr.Release(this.d2D1DrawInfo); ComPtr.Release(this.d2D1EffectContext); - // 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 < resourceTextureDescriptionCount; i++) + // 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++) { ComPtr.Release(this.resourceTextureManagerBuffer[i]); } From 11d1ad92cf0334bb0f8bd22072cc419858d6fbd5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 7 Oct 2023 12:30:16 +0200 Subject: [PATCH 07/11] Use Marshal.GetHRForException everywhere --- .../D2D1TransformMapperImpl.ID2D1TransformMapper.cs | 6 +++--- .../Interop/ID3D12MemoryAllocatorFactoryImpl.cs | 2 +- .../Interop/IWICStreamExtensions.IBufferWriter.cs | 4 ++-- .../Interop/IWICStreamExtensions.Stream.cs | 12 ++++++------ 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs index 6d302318..e3e616b8 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/TransformMappers/D2D1TransformMapperImpl.ID2D1TransformMapper.cs @@ -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(); diff --git a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs index 2795efa4..35aa47dc 100644 --- a/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs +++ b/src/ComputeSharp.D3D12MemoryAllocator/Interop/ID3D12MemoryAllocatorFactoryImpl.cs @@ -165,7 +165,7 @@ internal unsafe struct ID3D12MemoryAllocatorFactoryImpl } catch (Exception e) { - return e.HResult; + return Marshal.GetHRForException(e); } } } \ No newline at end of file diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.IBufferWriter.cs b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.IBufferWriter.cs index 54c34722..2f4de787 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.IBufferWriter.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.IBufferWriter.cs @@ -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); } } diff --git a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.Stream.cs b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.Stream.cs index c471afd5..9481099b 100644 --- a/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.Stream.cs +++ b/src/ComputeSharp/Graphics/Extensions/Interop/IWICStreamExtensions.Stream.cs @@ -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); } } From 73e0367951b5510b7665c727deb9f0f5e593a1a9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 7 Oct 2023 12:50:28 +0200 Subject: [PATCH 08/11] Use throw helpers in pixel shader effect, add more checks --- .../ArgumentOutOfRangeExceptionExtensions.cs | 32 +++++ ...lShaderEffect.ID2D1DrawTransformMethods.cs | 71 ++-------- ...ixelShaderEffect.ID2D1EffectImplMethods.cs | 113 ++++++---------- .../Effects/PixelShaderEffect.Properties.cs | 128 ++++-------------- 4 files changed, 116 insertions(+), 228 deletions(-) diff --git a/src/ComputeSharp.Core/Polyfills/ArgumentOutOfRangeExceptionExtensions.cs b/src/ComputeSharp.Core/Polyfills/ArgumentOutOfRangeExceptionExtensions.cs index 0e617bdf..1533c5cc 100644 --- a/src/ComputeSharp.Core/Polyfills/ArgumentOutOfRangeExceptionExtensions.cs +++ b/src/ComputeSharp.Core/Polyfills/ArgumentOutOfRangeExceptionExtensions.cs @@ -69,6 +69,22 @@ internal static class ArgumentOutOfRangeExceptionExtensions } } + /// + /// Throws an if is greater than or equal to . + /// + /// Dummy value to invoke the extension upon (always pass . + /// The argument to validate as less or equal than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + [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); + } + } + /// /// Throws an if is less than . /// @@ -118,6 +134,22 @@ internal static class ArgumentOutOfRangeExceptionExtensions } } + /// + /// Throws an if is not equal to a given other value. + /// + /// Dummy value to invoke the extension upon (always pass . + /// The argument to validate. + /// The value to compare against. + /// The name of the parameter with which corresponds. + [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); + } + } + /// /// Throws an if is not in the specified range. /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs index a87af065..cc0035b3 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -130,20 +130,12 @@ partial struct PixelShaderEffect try { - if (inputRectsCount != @this->GetGlobals().InputCount) - { - 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)) - { - return hresult; - } + @this->d2D1TransformMapper->MapOutputRectToInputRects(outputRect, inputRects, inputRectsCount).Assert(); } else { @@ -186,29 +178,21 @@ partial struct PixelShaderEffect try { - if (inputRectCount != @this->GetGlobals().InputCount) - { - return E.E_INVALIDARG; - } + default(ArgumentOutOfRangeException).ThrowIfNotEqual((int)inputRectCount, @this->GetGlobals().InputCount, nameof(inputRectCount)); if (@this->d2D1TransformMapper is not null) { using ComPtr d2D1DrawInfoUpdateContext = default; // Create an ID2D1DrawInfoUpdateContext instance - HRESULT hresult = D2D1DrawInfoUpdateContextImpl.Factory( + D2D1DrawInfoUpdateContextImpl.Factory( drawInfoUpdateContext: d2D1DrawInfoUpdateContext.GetAddressOf(), constantBuffer: @this->constantBuffer, constantBufferSize: @this->GetGlobals().ConstantBufferSize, - d2D1DrawInfo: @this->d2D1DrawInfo); - - if (!Windows.SUCCEEDED(hresult)) - { - return hresult; - } + d2D1DrawInfo: @this->d2D1DrawInfo).Assert(); // Forward the call to the input ID2D1TransformMapper instance - hresult = @this->d2D1TransformMapper->MapInputRectsToOutputRect( + HRESULT hresult = @this->d2D1TransformMapper->MapInputRectsToOutputRect( updateContext: (ID2D1DrawInfoUpdateContext*)d2D1DrawInfoUpdateContext.Get(), inputRects: inputRects, inputOpaqueSubRects: inputOpaqueSubRects, @@ -217,12 +201,10 @@ partial struct PixelShaderEffect outputOpaqueSubRect: outputOpaqueSubRect); // Regardless of the operation result, always invalidate the context - _ = d2D1DrawInfoUpdateContext.Get()->Close(); + d2D1DrawInfoUpdateContext.Get()->Close().Assert(); - if (!Windows.SUCCEEDED(hresult)) - { - return hresult; - } + // Now we can validate that the call was in fact successful + hresult.Assert(); } else if (inputRectCount == 0) { @@ -288,20 +270,12 @@ partial struct PixelShaderEffect try { - if (inputIndex >= (uint)@this->GetGlobals().InputCount) - { - 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)) - { - return hresult; - } + @this->d2D1TransformMapper->MapInvalidRect(inputIndex, invalidInputRect, invalidOutputRect).Assert(); } else { @@ -348,12 +322,7 @@ partial struct PixelShaderEffect D2D1PixelOptions pixelOptions = @this->GetGlobals().PixelOptions; // Set the pixel shader for the effect - HRESULT hresult = drawInfo->SetPixelShader(&shaderId, (D2D1_PIXEL_OPTIONS)pixelOptions); - - if (hresult != S.S_OK) - { - return hresult; - } + drawInfo->SetPixelShader(&shaderId, (D2D1_PIXEL_OPTIONS)pixelOptions).Assert(); // If any input descriptions are present, set them foreach (ref readonly D2D1InputDescription inputDescription in @this->GetGlobals().InputDescriptions.Span) @@ -362,12 +331,7 @@ partial struct PixelShaderEffect 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(); } D2D1BufferPrecision bufferPrecision = @this->GetGlobals().BufferPrecision; @@ -377,14 +341,9 @@ partial struct PixelShaderEffect if (bufferPrecision != D2D1BufferPrecision.Unknown || channelDepth != D2D1ChannelDepth.Default) { - hresult = drawInfo->SetOutputBuffer( + drawInfo->SetOutputBuffer( (D2D1_BUFFER_PRECISION)bufferPrecision, - (D2D1_CHANNEL_DEPTH)channelDepth); - - if (hresult != S.S_OK) - { - return hresult; - } + (D2D1_CHANNEL_DEPTH)channelDepth).Assert(); } return S.S_OK; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs index fea6cd51..f13cdbb2 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs @@ -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; @@ -89,12 +90,11 @@ internal unsafe partial struct PixelShaderEffect try { ReadOnlySpan bytecode = @this->GetGlobals().HlslBytecode.Span; - int hresult; fixed (Guid* pShaderId = &@this->GetGlobals().EffectId) fixed (byte* pBytecode = bytecode) { - hresult = effectContext->LoadPixelShader( + HRESULT hresult = effectContext->LoadPixelShader( shaderId: pShaderId, shaderBuffer: pBytecode, shaderBufferCount: (uint)bytecode.Length); @@ -106,27 +106,23 @@ internal unsafe partial struct PixelShaderEffect { 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 - if (Windows.SUCCEEDED(hresult)) - { - hresult = transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform); - } + transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform).Assert(); - // If the transform node was set, also store the effect context - if (Windows.SUCCEEDED(hresult)) - { - // Free the previous ID2D1EffectContext object, if present - ComPtr.Release(@this->d2D1EffectContext); + // Free the previous ID2D1EffectContext object, if present + ComPtr.Release(@this->d2D1EffectContext); - // Store the new ID2D1EffectContext object - _ = effectContext->AddRef(); + // Store the new ID2D1EffectContext object + _ = effectContext->AddRef(); - @this->d2D1EffectContext = effectContext; - } + @this->d2D1EffectContext = effectContext; - return hresult; + return S.S_OK; } catch (Exception e) { @@ -140,9 +136,10 @@ internal unsafe partial struct PixelShaderEffect { try { - int hresult = S.S_OK; - - // Validate the constant buffer + // 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) { @@ -152,64 +149,44 @@ internal unsafe partial struct PixelShaderEffect // First, set the constant buffer, if available if (@this->constantBuffer is not null) { - hresult = @this->d2D1DrawInfo->SetPixelShaderConstantBuffer( + @this->d2D1DrawInfo->SetPixelShaderConstantBuffer( buffer: @this->constantBuffer, - bufferCount: (uint)@this->GetGlobals().ConstantBufferSize); + bufferCount: (uint)@this->GetGlobals().ConstantBufferSize).Assert(); } - if (Windows.SUCCEEDED(hresult)) + ReadOnlySpan resourceTextureDescriptions = @this->GetGlobals().ResourceTextureDescriptions.Span; + + for (int i = 0; i < resourceTextureDescriptions.Length; i++) { - ReadOnlySpan resourceTextureDescriptions = @this->GetGlobals().ResourceTextureDescriptions.Span; + using ComPtr resourceTextureManager = @this->resourceTextureManagerBuffer[i]; - for (int i = 0; i < resourceTextureDescriptions.Length; 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) { - using ComPtr 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; - } - - using ComPtr 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; - } - - using ComPtr d2D1ResourceTexture = default; - - // Try to get the ID2D1ResourceTexture from the manager - hresult = resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf()); - - if (!Windows.SUCCEEDED(hresult)) - { - break; - } - - 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( - textureIndex: (uint)resourceTextureDescription.Index, - resourceTexture: d2D1ResourceTexture.Get()); - - if (!Windows.SUCCEEDED(hresult)) - { - break; - } + return E.E_NOT_VALID_STATE; } + + using ComPtr resourceTextureManagerInternal = default; + + // 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 d2D1ResourceTexture = default; + + // Try to get the ID2D1ResourceTexture from the manager + resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf()).Assert(); + + ref readonly D2D1ResourceTextureDescription resourceTextureDescription = ref resourceTextureDescriptions[i]; + + // Set the ID2D1ResourceTexture object to the current index in the ID2D1DrawInfo object in use + @this->d2D1DrawInfo->SetResourceTexture( + textureIndex: (uint)resourceTextureDescription.Index, + resourceTexture: d2D1ResourceTexture.Get()).Assert(); } - return hresult; + return S.S_OK; } catch (Exception e) { diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs index 862e24dd..6e124bd3 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs @@ -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; @@ -117,7 +118,8 @@ unsafe partial struct PixelShaderEffect try { - // This is a call likely from ID2D1Effect::GetValueSize, to query the property size + // 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) @@ -127,10 +129,7 @@ unsafe partial struct PixelShaderEffect return S.S_FALSE; } - if (data is null) - { - return E.E_POINTER; - } + default(ArgumentNullException).ThrowIfNull(data); if (dataSize < @this->GetGlobals().ConstantBufferSize) { @@ -172,15 +171,8 @@ unsafe partial struct PixelShaderEffect try { - if (data is null) - { - return E.E_POINTER; - } - - if (dataSize != (uint)@this->GetGlobals().ConstantBufferSize) - { - return E.E_INVALIDARG; - } + default(ArgumentNullException).ThrowIfNull(data); + default(ArgumentOutOfRangeException).ThrowIfNotEqual((int)dataSize, @this->GetGlobals().ConstantBufferSize, nameof(dataSize)); // Reuse the existing buffer if there is one, otherwise allocate a new one if (@this->constantBuffer is not null) @@ -212,15 +204,8 @@ unsafe partial struct PixelShaderEffect try { - if (data is null) - { - return E.E_POINTER; - } - - if (dataSize < sizeof(void*)) - { - return E.E_INVALIDARG; - } + default(ArgumentNullException).ThrowIfNull(data); + default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize)); if (@this->d2D1TransformMapper is null) { @@ -228,12 +213,7 @@ unsafe partial struct PixelShaderEffect } else { - HRESULT hresult = ((IUnknown*)@this->d2D1TransformMapper)->QueryInterface(Windows.__uuidof(), (void**)data); - - if (!Windows.SUCCEEDED(hresult)) - { - return hresult; - } + ((IUnknown*)@this->d2D1TransformMapper)->QueryInterface(Windows.__uuidof(), (void**)data).Assert(); } if (actualSize is not null) @@ -257,33 +237,18 @@ unsafe partial struct PixelShaderEffect try { - if (data is null) - { - return E.E_POINTER; - } + default(ArgumentNullException).ThrowIfNull(data); + default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize)); void* value = *(void**)data; - if (value is null) - { - return E.E_POINTER; - } - - if (dataSize != (uint)sizeof(void*)) - { - return E.E_INVALIDARG; - } + default(ArgumentNullException).ThrowIfNull(value); using ComPtr unknown = (IUnknown*)value; using ComPtr transformMapper = default; // Check that the input object implements ID2D1TransformMapper - int result = unknown.CopyTo(transformMapper.GetAddressOf()); - - if (result != S.S_OK) - { - return result; - } + unknown.CopyTo(transformMapper.GetAddressOf()).Assert(); // If there's already an existing manager, release it ComPtr.Release(@this->d2D1TransformMapper); @@ -311,29 +276,13 @@ unsafe partial struct PixelShaderEffect { try { - if (index >= GetGlobals().ResourceTextureCount) - { - return E.E_INVALIDARG; - } - - if (data is null) - { - return E.E_POINTER; - } - - if (dataSize < sizeof(void*)) - { - return E.E_INVALIDARG; - } + default(ArgumentNullException).ThrowIfNull(data); + default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize)); + default(ArgumentOutOfRangeException).ThrowIfGreaterThanOrEqual(index, GetGlobals().ResourceTextureCount); using ComPtr resourceTextureManager = this.resourceTextureManagerBuffer[index]; - HRESULT hresult = resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data); - - if (!Windows.SUCCEEDED(hresult)) - { - return hresult; - } + resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data).Assert(); if (actualSize is not null) { @@ -359,65 +308,36 @@ unsafe partial struct PixelShaderEffect { try { - if (index >= GetGlobals().ResourceTextureCount) - { - return E.E_INVALIDARG; - } - - if (data is null) - { - return E.E_POINTER; - } + default(ArgumentNullException).ThrowIfNull(data); + default(ArgumentOutOfRangeException).ThrowIfLessThan((int)dataSize, sizeof(void*), nameof(dataSize)); + default(ArgumentOutOfRangeException).ThrowIfGreaterThanOrEqual(index, GetGlobals().ResourceTextureCount); void* value = *(void**)data; - if (value is null) - { - return E.E_POINTER; - } - - if (dataSize != (uint)sizeof(void*)) - { - return E.E_INVALIDARG; - } + default(ArgumentNullException).ThrowIfNull(value); using ComPtr unknown = (IUnknown*)value; using ComPtr resourceTextureManager = default; // Check that the input object implements ID2D1ResourceTextureManager - int result = unknown.CopyTo(resourceTextureManager.GetAddressOf()); - - if (result != S.S_OK) - { - return result; - } + unknown.CopyTo(resourceTextureManager.GetAddressOf()).Assert(); using ComPtr resourceTextureManagerInternal = default; // Then, also check that it implements ID2D1ResourceTextureManagerInternal - result = unknown.CopyTo(resourceTextureManagerInternal.GetAddressOf()); - - if (result != S.S_OK) - { - return result; - } + unknown.CopyTo(resourceTextureManagerInternal.GetAddressOf()).Assert(); // Initialize the resource texture manager, if an effect context is available if (this.d2D1EffectContext is not null) { uint dimensions = (uint)GetGlobals().ResourceTextureDescriptions.Span[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)) - { - return result; - } + resourceTextureManagerInternal.Get()->Initialize(this.d2D1EffectContext, &dimensions).Assert(); } ref ID2D1ResourceTextureManager* currentResourceTextureManager = ref this.resourceTextureManagerBuffer[index]; From 2022a73754f7caf2d6b91992d96a3f078677d86c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 7 Oct 2023 19:57:48 +0200 Subject: [PATCH 09/11] Improve PixelShaderEffect.Factory method --- .../Interop/Effects/PixelShaderEffect.cs | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index fb3a2acf..38e87929 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -150,8 +150,22 @@ internal unsafe partial struct PixelShaderEffect { @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 (Exception) + catch (Exception e) { // Free the effect, if we have one NativeMemory.Free(@this); @@ -164,24 +178,8 @@ internal unsafe partial struct PixelShaderEffect *effectImpl = null; - return E.E_OUTOFMEMORY; + return Marshal.GetHRForException(e); } - - *@this = default; - - @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; } /// From cfbfc2886b399ba4463f1067e26993d03438a6cd Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 7 Oct 2023 20:28:19 +0200 Subject: [PATCH 10/11] More code refactoring and style tweaks --- ...lShaderEffect.ID2D1DrawTransformMethods.cs | 7 +--- ...ixelShaderEffect.ID2D1EffectImplMethods.cs | 7 +--- ...mpl.ID2D1ResourceTextureManagerInternal.cs | 7 ++-- src/TerraFX.Interop.Windows/ComPtr`1.cs | 33 +++++++++++++++++++ 4 files changed, 37 insertions(+), 17 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs index cc0035b3..94367676 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1DrawTransformMethods.cs @@ -310,13 +310,8 @@ partial struct PixelShaderEffect try { - // Free the previous ID2D1DrawInfo object, if present - ComPtr.Release(@this->d2D1DrawInfo); - // Store the new ID2D1DrawInfo object - _ = drawInfo->AddRef(); - - @this->d2D1DrawInfo = drawInfo; + ComPtr.CopyTo(drawInfo, ref @this->d2D1DrawInfo); Guid shaderId = @this->GetGlobals().EffectId; D2D1PixelOptions pixelOptions = @this->GetGlobals().PixelOptions; diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs index f13cdbb2..18c454be 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs @@ -114,13 +114,8 @@ internal unsafe partial struct PixelShaderEffect // If loading the bytecode succeeded, set the transform node transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform).Assert(); - // Free the previous ID2D1EffectContext object, if present - ComPtr.Release(@this->d2D1EffectContext); - // Store the new ID2D1EffectContext object - _ = effectContext->AddRef(); - - @this->d2D1EffectContext = effectContext; + ComPtr.CopyTo(effectContext, ref @this->d2D1EffectContext); return S.S_OK; } diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs index 1b8a84ed..99aa3985 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs @@ -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.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.WriteTo(@this->d2D1ResourceTexture, out *resourceTexture); return S.S_OK; } diff --git a/src/TerraFX.Interop.Windows/ComPtr`1.cs b/src/TerraFX.Interop.Windows/ComPtr`1.cs index abb74bcc..58582622 100644 --- a/src/TerraFX.Interop.Windows/ComPtr`1.cs +++ b/src/TerraFX.Interop.Windows/ComPtr`1.cs @@ -51,6 +51,39 @@ internal unsafe struct ComPtr : IDisposable } } + /// + /// Copies a given COM object into a target destination. + /// + /// The input COM object to copy. + /// The target destination for the COM object. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void CopyTo(T* obj, ref T* other) + { + T* pointer = other; + + if (pointer is not null) + { + _ = ((IUnknown*)pointer)->Release(); + } + + _ = ((IUnknown*)obj)->AddRef(); + + other = obj; + } + + /// + /// Writes a given COM object into a target (assumed uninitialized) destination. + /// + /// The input COM object to copy. + /// The target destination for the COM object. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteTo(T* obj, out T* other) + { + _ = ((IUnknown*)obj)->AddRef(); + + other = obj; + } + /// Converts a raw pointer to a new instance and increments the ref count. /// The raw pointer to wrap. [MethodImpl(MethodImplOptions.AggressiveInlining)] From 9fbae2968e91c8350ce5a194d2613e1ecf29ed37 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 Oct 2023 17:11:36 +0200 Subject: [PATCH 11/11] Fix a bug in ComPtr.CopyTo when targeting same object --- src/TerraFX.Interop.Windows/ComPtr`1.cs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/TerraFX.Interop.Windows/ComPtr`1.cs b/src/TerraFX.Interop.Windows/ComPtr`1.cs index 58582622..4f1a3273 100644 --- a/src/TerraFX.Interop.Windows/ComPtr`1.cs +++ b/src/TerraFX.Interop.Windows/ComPtr`1.cs @@ -52,13 +52,25 @@ internal unsafe struct ComPtr : IDisposable } /// - /// Copies a given COM object into a target destination. + /// Copies a given COM object into a target destination, incrementing reference counts where needed. /// /// The input COM object to copy. /// The target destination for the COM object. [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) @@ -66,13 +78,11 @@ internal unsafe struct ComPtr : IDisposable _ = ((IUnknown*)pointer)->Release(); } - _ = ((IUnknown*)obj)->AddRef(); - other = obj; } /// - /// Writes a given COM object into a target (assumed uninitialized) destination. + /// Writes a given COM object into a target (assumed uninitialized) destination, incrementing reference counts where needed. /// /// The input COM object to copy. /// The target destination for the COM object.