diff --git a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs
index cdc4e71c..b62ce00f 100644
--- a/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs
+++ b/src/ComputeSharp.D2D1.Uwp/ABI.Microsoft.Graphics.Canvas/ICanvasImageInterop.cs
@@ -21,7 +21,7 @@ internal unsafe interface ICanvasImageInterop
/// The for the operation.
[PreserveSig]
[return: NativeTypeName("HRESULT")]
- int GetDevice([NativeTypeName("ICanvasDevice**")] IUnknown** device);
+ int GetDevice(ICanvasDevice** device);
///
/// Gets an from an instance.
@@ -51,7 +51,7 @@ internal unsafe interface ICanvasImageInterop
[PreserveSig]
[return: NativeTypeName("HRESULT")]
int GetD2DImage(
- [NativeTypeName("ICanvasDevice*")] IUnknown* device,
+ ICanvasDevice* device,
ID2D1DeviceContext* deviceContext,
CanvasImageGetD2DImageFlags flags,
float targetDpi,
diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs
new file mode 100644
index 00000000..9cdc9de8
--- /dev/null
+++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ICanvasDeviceExtensions.cs
@@ -0,0 +1,38 @@
+using ABI.Microsoft.Graphics.Canvas;
+using ComputeSharp.D2D1.Extensions;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+using Win32 = TerraFX.Interop.Windows.Windows;
+
+namespace ComputeSharp.D2D1.Uwp.Extensions;
+
+///
+/// A with extensions for the type.
+///
+internal static unsafe class ICanvasDeviceExtensions
+{
+ ///
+ /// Gets the underlying object from an object.
+ ///
+ /// The input object.
+ /// The underlying object for .
+ /// The for the operation.
+ public static HRESULT GetD2DDevice(this ref ICanvasDevice canvasDevice, ID2D1Device1** d2D1Device1)
+ {
+ using ComPtr canvasDeviceResourceWrapperNative = default;
+
+ // Get the ICanvasResourceWrapperNative wrapper around the input device
+ canvasDevice.QueryInterface(
+ riid: Win32.__uuidof(),
+ ppvObject: (void**)canvasDeviceResourceWrapperNative.GetAddressOf()).Assert();
+
+ // Get the underlying ID2D1Device1 instance in use
+ HRESULT hresult = canvasDeviceResourceWrapperNative.Get()->GetNativeResource(
+ device: null,
+ dpi: 0,
+ iid: Win32.__uuidof(),
+ resource: (void**)d2D1Device1);
+
+ return hresult;
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.Uwp/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.D2D1.Uwp/Extensions/ID3D12DeviceExtensions.cs
new file mode 100644
index 00000000..5e6b46fb
--- /dev/null
+++ b/src/ComputeSharp.D2D1.Uwp/Extensions/ID3D12DeviceExtensions.cs
@@ -0,0 +1,60 @@
+using ComputeSharp.D2D1.Extensions;
+using TerraFX.Interop.DirectX;
+using TerraFX.Interop.Windows;
+
+namespace ComputeSharp.D2D1.Uwp.Extensions;
+
+///
+/// A with extensions for the type.
+///
+internal static unsafe class ID2D1DeviceContextExtensions
+{
+ ///
+ /// Checks whether a given has an as render target.
+ ///
+ /// The input instance to check.
+ /// Whether the target of is an .
+ public static bool HasCommandListTarget(this ref ID2D1DeviceContext deviceContext)
+ {
+ using ComPtr d2D1Image = default;
+
+ // First get the target and check that it is not null
+ deviceContext.GetTarget(d2D1Image.GetAddressOf());
+
+ if (d2D1Image.Get() is null)
+ {
+ return false;
+ }
+
+ using ComPtr d2D1CommandList = default;
+
+ // If there is a target, check if it is an ID2D1CommandList
+ HRESULT hresult = d2D1Image.CopyTo(d2D1CommandList.GetAddressOf());
+
+ // Special case E_NOINTERFACE: this should return false and it's not an error
+ if (hresult == E.E_NOINTERFACE)
+ {
+ return false;
+ }
+
+ // Throw for any other failure
+ hresult.Assert();
+
+ return true;
+ }
+
+ ///
+ /// Reads the DPI value from a target object.
+ ///
+ /// The input instance.
+ /// The DPIs from .
+ public static float GetDpi(this ref ID2D1DeviceContext deviceContext)
+ {
+ float dpiX;
+ float dpiY;
+
+ deviceContext.GetDpi(&dpiX, &dpiY);
+
+ return dpiX;
+ }
+}
\ No newline at end of file
diff --git a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs
index 2babeb23..49ca9198 100644
--- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs
+++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.ReferenceTracking.cs
@@ -47,6 +47,8 @@ partial class PixelShaderEffect
///
void IReferenceTrackedObject.DangerousOnDispose()
{
- // TODO
+ this.canvasDevice.Dispose();
+ this.d2D1RealizationDevice.Dispose();
+ this.d2D1Effect.Dispose();
}
}
\ 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 f6f7613e..d8b95f47 100644
--- a/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs
+++ b/src/ComputeSharp.D2D1.Uwp/PixelShaderEffect{T}.cs
@@ -1,12 +1,16 @@
-using ABI.Microsoft.Graphics.Canvas;
-using Microsoft.Graphics.Canvas;
-using System.Numerics;
using System;
-using Windows.Foundation;
-using TerraFX.Interop.Windows;
-using TerraFX.Interop.DirectX;
-using ComputeSharp.D2D1.Interop;
+using System.Numerics;
+using System.Threading;
+using ABI.Microsoft.Graphics.Canvas;
using ComputeSharp.D2D1.Extensions;
+using ComputeSharp.D2D1.Interop;
+using ComputeSharp.D2D1.Uwp.Extensions;
+using ComputeSharp.Interop;
+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;
@@ -14,89 +18,253 @@ namespace ComputeSharp.D2D1.Uwp;
/// A custom implementation powered by a supplied shader type.
///
/// The type of shader to use to render frames.
-public sealed class PixelShaderEffect : ICanvasImage, ICanvasImageInterop
+public sealed partial class PixelShaderEffect : IReferenceTrackedObject, ICanvasImage, ICanvasImageInterop
where T : unmanaged, ID2D1PixelShader
{
+ ///
+ /// The value for the current instance.
+ ///
+ private ReferenceTracker referenceTracker;
+
+ ///
+ /// Lock object used to synchronize calls to APIs.
+ ///
+ private readonly object lockObject = new();
+
+ ///
+ /// Flag to track whether a given call is recursively invoked by , to avoid graph cycles.
+ ///
+ private volatile int isInsideGetD2DImage;
+
+ ///
+ /// The current device the effect is realized on, if one is available (this is the underlying COM object for ).
+ ///
+ private ComPtr canvasDevice;
+
+ ///
+ /// The underlying D2D1 device the effect is realized on, if one is available (this is the D2D device backing ).
+ ///
+ private ComPtr d2D1RealizationDevice;
+
+ ///
+ /// The current realized , if one is available.
+ ///
+ private ComPtr d2D1Effect;
+
///
/// The current value in use.
///
public T Value;
- private ComPtr effect;
-
- ///
- public void Dispose()
- {
- }
-
///
Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator)
{
- throw new NotImplementedException();
+ throw new NotSupportedException();
}
///
Rect ICanvasImage.GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform)
{
- throw new NotImplementedException();
+ throw new NotSupportedException();
}
///
- unsafe int ICanvasImageInterop.GetDevice(IUnknown** device)
+ unsafe int ICanvasImageInterop.GetDevice(ICanvasDevice** device)
{
- return S.S_OK;
+ 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(
- IUnknown* device,
+ ICanvasDevice* device,
ID2D1DeviceContext* deviceContext,
CanvasImageGetD2DImageFlags flags,
float targetDpi,
float* realizeDpi,
ID2D1Image** ppImage)
{
- if (realizeDpi is not null)
+ using ReferenceTracker.Lease _0 = GetReferenceTracker().TryGetLease(out bool leaseTaken);
+
+ // Check for disposal
+ if (!leaseTaken)
{
- *realizeDpi = 0;
+ return RO.RO_E_CLOSED;
+ }
+
+ // Check for graph cycles
+ if (Interlocked.CompareExchange(ref this.isInsideGetD2DImage, 1, 0) == 1)
+ {
+ return D2DERR.D2DERR_CYCLIC_GRAPH;
}
try
{
- if (this.effect.Get() is null)
+ // Lock after checking for graph cycles (other public APIs also lock on this object)
+ lock (this.lockObject)
{
- using ComPtr d2D1Factory = default;
+ // 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;
+ }
- deviceContext->GetFactory(d2D1Factory.GetAddressOf());
+ 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();
+ }
- using ComPtr d2D1Factory1 = default;
+ // ReadDpiFromDeviceContext has been processed, so it can be removed now
+ flags &= ~CanvasImageGetD2DImageFlags.ReadDpiFromDeviceContext;
+ }
- d2D1Factory.CopyTo(d2D1Factory1.GetAddressOf()).Assert();
+ using ComPtr d2D1Device1 = default;
- D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _);
+ // Get the underlying ID2D1Device1 instance in use
+ device->GetD2DDevice(d2D1Device1.GetAddressOf()).Assert();
- using ComPtr d2D1Effect = default;
+ // 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();
- D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect.GetAddressOf());
+ // Store the input realization device and canvas device for future uses
+ d2D1Device1.CopyTo(ref this.d2D1RealizationDevice).Assert();
- D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, d2D1Effect.Get());
+ fixed (ICanvasDevice** canvasDevice = this.canvasDevice)
+ {
+ device->QueryInterface(Win32.__uuidof(), (void**)canvasDevice).Assert();
+ }
+ }
- this.effect = new(d2D1Effect.Get());
+ // 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);
+ }
- d2D1Effect.CopyTo(ppImage).Assert();
+ // 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;
}
- else
- {
- D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in this.Value, this.effect.Get());
-
- this.effect.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;
+ }
+
+ // TODO
+ }
+
+ ///
+ /// 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();
+
+ // Register the effect with the factory (TODO: only do this if needed)
+ D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory1.Get(), out _);
+
+ fixed (ID2D1Effect** d2D1Effect = this.d2D1Effect)
+ {
+ // Create an instance of the effect in use and store it in the current object
+ D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(deviceContext, (void**)d2D1Effect);
+ }
+
+ // 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
diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1CommandList.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1CommandList.cs
new file mode 100644
index 00000000..184b8c3f
--- /dev/null
+++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1CommandList.cs
@@ -0,0 +1,17 @@
+// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
+
+// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22621.0
+// Original source is Copyright © Microsoft. All rights reserved.
+
+using System;
+using System.Runtime.InteropServices;
+
+namespace TerraFX.Interop.DirectX;
+
+[Guid("B4F34A19-2383-4D76-94F6-EC343657C3DC")]
+[NativeTypeName("struct ID2D1CommandList : ID2D1Image")]
+[NativeInheritance("ID2D1Image")]
+internal unsafe partial struct ID2D1CommandList
+{
+ public void** lpVtbl;
+}
\ No newline at end of file
diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs
index f2c97599..620225ba 100644
--- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs
+++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1DeviceContext.cs
@@ -26,10 +26,24 @@ internal unsafe partial struct ID2D1DeviceContext
((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), factory);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [VtblIndex(52)]
+ public void GetDpi(float* dpiX, float* dpiY)
+ {
+ ((delegate* unmanaged[Stdcall])(lpVtbl[52]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), dpiX, dpiY);
+ }
+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(63)]
public HRESULT CreateEffect([NativeTypeName("const IID &")] Guid* effectId, ID2D1Effect** effect)
{
return ((delegate* unmanaged[Stdcall])(lpVtbl[63]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), effectId, effect);
}
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [VtblIndex(75)]
+ public void GetTarget(ID2D1Image** image)
+ {
+ ((delegate* unmanaged[Stdcall])(lpVtbl[75]))((ID2D1DeviceContext*)Unsafe.AsPointer(ref this), image);
+ }
}
\ No newline at end of file
diff --git a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems
index dbd3fde5..537c5701 100644
--- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems
+++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems
@@ -33,6 +33,7 @@
+
diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs
index 5a3c371b..d11c5f59 100644
--- a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs
+++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs
@@ -9,4 +9,7 @@ internal static partial class D2DERR
{
[NativeTypeName("#define D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES _HRESULT_TYPEDEF_(0x88990026L)")]
public const int D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES = unchecked((int)(0x88990026));
+
+ [NativeTypeName("#define D2DERR_CYCLIC_GRAPH _HRESULT_TYPEDEF_(0x88990020L)")]
+ public const int D2DERR_CYCLIC_GRAPH = unchecked((int)(0x88990020));
}
\ No newline at end of file