From 1c2ff9a2ef222c747958c4c252cf5bcd8fc5b6b1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 24 Oct 2022 01:37:04 +0200 Subject: [PATCH] Move ICanvasImageInterop implementation into partial file --- ...ixelShaderEffect{T}.ICanvasImageInterop.cs | 266 ++++++++++++++++++ .../PixelShaderEffect{T}.cs | 251 ----------------- 2 files changed, 266 insertions(+), 251 deletions(-) create mode 100644 src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs new file mode 100644 index 00000000..f7235629 --- /dev/null +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ICanvasImageInterop.cs @@ -0,0 +1,266 @@ +using System; +using System.Threading; +using ABI.Microsoft.Graphics.Canvas; +using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Interop.Effects; +using ComputeSharp.D2D1.Uwp.Extensions; +using ComputeSharp.Interop; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using Win32 = TerraFX.Interop.Windows.Windows; + +namespace ComputeSharp.D2D1.Uwp; + +/// +unsafe partial class PixelShaderEffect +{ + /// + int ICanvasImageInterop.GetDevice(ICanvasDevice** device) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); + + // Check for disposal + if (!leaseTaken) + { + return RO.RO_E_CLOSED; + } + + // Ensure we can take a lock without blocking. We can't access the realization device with no + // lock, as that could lead to memory leaks or corruption if GetD2DImage was to manipulate that + // field concurrently. We also cannot lock directly, because that would deadlock if someone was + // to (incorrectly) try to use the same effect from two different threads. To protect against + // that, we try to lock, and just return E_NOT_VALID_STATE if another thread holds the lock. If + // this call had GetD2DImage in the stack, that would work fine because locks are recursive. + if (!Monitor.TryEnter(this.lockObject)) + { + return E.E_NOT_VALID_STATE; + } + + try + { + // Copy the device over to the target + return this.canvasDevice.CopyTo(device); + } + finally + { + Monitor.Exit(this.lockObject); + } + } + + /// + int ICanvasImageInterop.GetD2DImage( + ICanvasDevice* device, + ID2D1DeviceContext* deviceContext, + CanvasImageGetD2DImageFlags flags, + float targetDpi, + float* realizeDpi, + ID2D1Image** ppImage) + { + using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); + + // Check for disposal + if (!leaseTaken) + { + return RO.RO_E_CLOSED; + } + + // Check for graph cycles + if (Interlocked.CompareExchange(ref this.isInsideGetD2DImage, 1, 0) == 1) + { + return D2DERR.D2DERR_CYCLIC_GRAPH; + } + + try + { + // Lock after checking for graph cycles (other public APIs also lock on this object) + lock (this.lockObject) + { + // Process the ReadDpiFromDeviceContext flag (same logic as CanvasEffect::GetD2DImage) + if ((flags & CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext) != CanvasImageGetD2DImageFlags.None) + { + // If ReadDpiFromDeviceContext is used, the context cannot be null + if (deviceContext is null) + { + return E.E_POINTER; + } + + if (deviceContext->HasCommandListTarget()) + { + // Command lists are DPI dependent, so DPI compensation effects are always needed + flags |= CanvasImageGetD2DImageFlags.AlwaysInsertDpiCompensation; + } + else + { + // If the effect is not being drawn onto a command list, the DPIs can be read from the device context + targetDpi = deviceContext->GetDpi(); + } + + // ReadDpiFromDeviceContext has been processed, so it can be removed now + flags &= ~CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext; + } + + using ComPtr d2D1Device1 = default; + + // Get the underlying ID2D1Device1 instance in use + device->GetD2DDevice(d2D1Device1.GetAddressOf()).Assert(); + + // Check that the input D2D device is the same instance as the current realization device, if any. + // If not and the effect has already been realized, unrealize it and store the new device to use. + if (!d2D1Device1.IsSameInstance(in this.d2D1RealizationDevice)) + { + Unrealize(); + + // Store the input realization device and canvas device for future uses + d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert(); + + fixed (ICanvasDevice** canvasDevice = this.canvasDevice) + { + device->QueryInterface(Win32.__uuidof(), (void**)canvasDevice).Assert(); + } + } + + // Create the effect, if it doesn't exist already + if (this.d2D1Effect.Get() is null) + { + Realize(flags, targetDpi, deviceContext); + } + else if (!flags.HasFlag(CanvasImageGetD2DImageFlags.MinimalRealization)) + { + // Recurse through the effect graph and ensure all nodes are initialized + RefreshInputs(flags, targetDpi, deviceContext); + } + + // The realized DPIs are always 0 for pixel shader effects + if (realizeDpi is not null) + { + *realizeDpi = 0; + } + + this.d2D1Effect.CopyTo(ppImage).Assert(); + + return S.S_OK; + } + } + catch (Exception e) + { + *ppImage = null; + + return e.HResult; + } + finally + { + // Ensure that reset this flag so that this method can be called again + this.isInsideGetD2DImage = 0; + } + } + + /// + /// Unrealizes the currently realized object. + /// + private void Unrealize() + { + // If there is no ID2D1Effect object, there is nothing left to do + if (this.d2D1Effect.Get() is null) + { + return; + } + + // Cache the last update value of the cache and precision properties + this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); + this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); + + // TODO: read back D2D sources from the effect + + // Finally release the effect as well + this.d2D1Effect.Dispose(); + } + + /// + /// Realizes the underlying for this object. + /// + /// The current flags in use. + /// The target DPI in use. + /// The instance in use. + private void Realize(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + { + using ComPtr d2D1Factory = default; + + // Get the underlying ID2D1Factory from the input context, so we can register and create the effect + deviceContext->GetFactory(d2D1Factory.GetAddressOf()); + + using ComPtr d2D1Factory1 = default; + + // D2D1PixelShaderEffect APIs specifically need an ID2D1Factory1 (as ID2D1Factory1::RegisterEffectFromString is used) + d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); + + bool isPossiblyRegistered = true; + + // If the effect hasn't been initialized explicitly, initialize it now + if (!PixelShaderEffect.For.TryGetId(out Guid effectId)) + { + PixelShaderEffect.For.Initialize(null); + + effectId = PixelShaderEffect.For.Id; + isPossiblyRegistered = false; + } + + fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect) + { + HRESULT hresult = D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED; + + // Try to create an instance of the effect in use and store it in the current object + if (isPossiblyRegistered) + { + hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); + } + + // Check if creation failed due to the effect not being registered. In that case, register + // it and then try again. This is much faster than check whether the effect is registered + // manually every time, by enumerating all registered effects for the target device context. + if (hresult == D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED) + { + // Register the effect with the factory (pass the same D2D1 draw transform mapper factory that was used before) + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), PixelShaderEffect.For.D2D1DrawTransformMapperFactory, out _); + + // Try to create the effect again + hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); + } + + // Rethrow any other errors + hresult.Assert(); + } + + // TODO: transfer properties (eg. D2D1ResourceTextureManager-s) + + // If cache input has been set, forward that to the new effect + if (this.cacheOutput) + { + this.d2D1Effect.Get()->SetCachedProperty(true); + } + + // If the buffer precision isn't unknown, forward that as well + if (this.d2D1BufferPrecision != D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN) + { + this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); + } + + // TODO: port base CanvasEffect::Realize logic + + // Also set the current constants for the effect + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); + } + + /// + /// Updates the draw state for the currently realized effect. + /// + /// The current flags in use. + /// The target DPI in use. + /// The instance in use. + private void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) + { + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); + + // TODO + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs index 3a3d2cdc..2069042c 100644 --- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs +++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs @@ -1,9 +1,6 @@ using System; using System.Numerics; -using System.Threading; using ABI.Microsoft.Graphics.Canvas; -using ComputeSharp.D2D1.Extensions; -using ComputeSharp.D2D1.Interop; using ComputeSharp.D2D1.Interop.Effects; using ComputeSharp.D2D1.Uwp.Extensions; using ComputeSharp.Interop; @@ -11,7 +8,6 @@ using Microsoft.Graphics.Canvas; using Windows.Foundation; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -using Win32 = TerraFX.Interop.Windows.Windows; namespace ComputeSharp.D2D1.Uwp; @@ -185,251 +181,4 @@ public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICan { throw new NotSupportedException(); } - - /// - unsafe int ICanvasImageInterop.GetDevice(ICanvasDevice** device) - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); - - // Check for disposal - if (!leaseTaken) - { - return RO.RO_E_CLOSED; - } - - // Ensure we can take a lock without blocking. We can't access the realization device with no - // lock, as that could lead to memory leaks or corruption if GetD2DImage was to manipulate that - // field concurrently. We also cannot lock directly, because that would deadlock if someone was - // to (incorrectly) try to use the same effect from two different threads. To protect against - // that, we try to lock, and just return E_NOT_VALID_STATE if another thread holds the lock. If - // this call had GetD2DImage in the stack, that would work fine because locks are recursive. - if (!Monitor.TryEnter(this.lockObject)) - { - return E.E_NOT_VALID_STATE; - } - - try - { - // Copy the device over to the target - return this.canvasDevice.CopyTo(device); - } - finally - { - Monitor.Exit(this.lockObject); - } - } - - /// - unsafe int ICanvasImageInterop.GetD2DImage( - ICanvasDevice* device, - ID2D1DeviceContext* deviceContext, - CanvasImageGetD2DImageFlags flags, - float targetDpi, - float* realizeDpi, - ID2D1Image** ppImage) - { - using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken); - - // Check for disposal - if (!leaseTaken) - { - return RO.RO_E_CLOSED; - } - - // Check for graph cycles - if (Interlocked.CompareExchange(ref this.isInsideGetD2DImage, 1, 0) == 1) - { - return D2DERR.D2DERR_CYCLIC_GRAPH; - } - - try - { - // Lock after checking for graph cycles (other public APIs also lock on this object) - lock (this.lockObject) - { - // Process the ReadDpiFromDeviceContext flag (same logic as CanvasEffect::GetD2DImage) - if ((flags & CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext) != CanvasImageGetD2DImageFlags.None) - { - // If ReadDpiFromDeviceContext is used, the context cannot be null - if (deviceContext is null) - { - return E.E_POINTER; - } - - if (deviceContext->HasCommandListTarget()) - { - // Command lists are DPI dependent, so DPI compensation effects are always needed - flags |= CanvasImageGetD2DImageFlags.AlwaysInsertDpiCompensation; - } - else - { - // If the effect is not being drawn onto a command list, the DPIs can be read from the device context - targetDpi = deviceContext->GetDpi(); - } - - // ReadDpiFromDeviceContext has been processed, so it can be removed now - flags &= ~CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext; - } - - using ComPtr d2D1Device1 = default; - - // Get the underlying ID2D1Device1 instance in use - device->GetD2DDevice(d2D1Device1.GetAddressOf()).Assert(); - - // Check that the input D2D device is the same instance as the current realization device, if any. - // If not and the effect has already been realized, unrealize it and store the new device to use. - if (!d2D1Device1.IsSameInstance(in this.d2D1RealizationDevice)) - { - Unrealize(); - - // Store the input realization device and canvas device for future uses - d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert(); - - fixed (ICanvasDevice** canvasDevice = this.canvasDevice) - { - device->QueryInterface(Win32.__uuidof(), (void**)canvasDevice).Assert(); - } - } - - // Create the effect, if it doesn't exist already - if (this.d2D1Effect.Get() is null) - { - Realize(flags, targetDpi, deviceContext); - } - else if (!flags.HasFlag(CanvasImageGetD2DImageFlags.MinimalRealization)) - { - // Recurse through the effect graph and ensure all nodes are initialized - RefreshInputs(flags, targetDpi, deviceContext); - } - - // The realized DPIs are always 0 for pixel shader effects - if (realizeDpi is not null) - { - *realizeDpi = 0; - } - - this.d2D1Effect.CopyTo(ppImage).Assert(); - - return S.S_OK; - } - } - catch (Exception e) - { - *ppImage = null; - - return e.HResult; - } - finally - { - // Ensure that reset this flag so that this method can be called again - this.isInsideGetD2DImage = 0; - } - } - - /// - /// Unrealizes the currently realized object. - /// - private unsafe void Unrealize() - { - // If there is no ID2D1Effect object, there is nothing left to do - if (this.d2D1Effect.Get() is null) - { - return; - } - - // Cache the last update value of the cache and precision properties - this.cacheOutput = this.d2D1Effect.Get()->GetCachedProperty(); - this.d2D1BufferPrecision = this.d2D1Effect.Get()->GetPrecisionProperty(); - - // TODO: read back D2D sources from the effect - - // Finally release the effect as well - this.d2D1Effect.Dispose(); - } - - /// - /// Realizes the underlying for this object. - /// - /// The current flags in use. - /// The target DPI in use. - /// The instance in use. - private unsafe void Realize(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) - { - using ComPtr d2D1Factory = default; - - // Get the underlying ID2D1Factory from the input context, so we can register and create the effect - deviceContext->GetFactory(d2D1Factory.GetAddressOf()); - - using ComPtr d2D1Factory1 = default; - - // D2D1PixelShaderEffect APIs specifically need an ID2D1Factory1 (as ID2D1Factory1::RegisterEffectFromString is used) - d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert(); - - bool isPossiblyRegistered = true; - - // If the effect hasn't been initialized explicitly, initialize it now - if (!PixelShaderEffect.For.TryGetId(out Guid effectId)) - { - PixelShaderEffect.For.Initialize(null); - - effectId = PixelShaderEffect.For.Id; - isPossiblyRegistered = false; - } - - fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect) - { - HRESULT hresult = D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED; - - // Try to create an instance of the effect in use and store it in the current object - if (isPossiblyRegistered) - { - hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); - } - - // Check if creation failed due to the effect not being registered. In that case, register - // it and then try again. This is much faster than check whether the effect is registered - // manually every time, by enumerating all registered effects for the target device context. - if (hresult == D2DERR.D2DERR_EFFECT_IS_NOT_REGISTERED) - { - // Register the effect with the factory (pass the same D2D1 draw transform mapper factory that was used before) - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), PixelShaderEffect.For.D2D1DrawTransformMapperFactory, out _); - - // Try to create the effect again - hresult = deviceContext->CreateEffect(effectId: &effectId, effect: d2D1Effect); - } - - // Rethrow any other errors - hresult.Assert(); - } - - // If cache input has been set, forward that to the new effect - if (this.cacheOutput) - { - this.d2D1Effect.Get()->SetCachedProperty(true); - } - - // If the buffer precision isn't unknown, forward that as well - if (this.d2D1BufferPrecision != D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN) - { - this.d2D1Effect.Get()->SetPrecisionProperty(this.d2D1BufferPrecision); - } - - // TODO: port base CanvasEffect::Realize logic - - // Also set the current constants for the effect - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); - } - - /// - /// Updates the draw state for the currently realized effect. - /// - /// The current flags in use. - /// The target DPI in use. - /// The instance in use. - private unsafe void RefreshInputs(CanvasImageGetD2DImageFlags flags, float targetDpi, ID2D1DeviceContext* deviceContext) - { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.d2D1Effect.Get()); - - // TODO - } } \ No newline at end of file