From 6b330d1973d56b4623d55e0819ef6e94a52fcbe6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 15 Apr 2023 18:42:01 +0200 Subject: [PATCH] Add basic WASDK sample setup and render loop --- .../ICanvasFactoryNative.cs | 90 +++++ .../Backend/Win32Application.cs | 184 ++++++++++ .../Backend/Win32ApplicationRunner.cs | 344 ++++++++++++++++++ .../ComputeSharp.SwapChain.D2D1.csproj | 8 +- .../ComputeSharp.SwapChain.D2D1/Program.cs | 3 + .../Backend/Win32ApplicationRunner.cs | 1 + 6 files changed, 629 insertions(+), 1 deletion(-) create mode 100644 samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs create mode 100644 samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs create mode 100644 samples/ComputeSharp.SwapChain.D2D1/Backend/Win32ApplicationRunner.cs create mode 100644 samples/ComputeSharp.SwapChain.D2D1/Program.cs diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs b/samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs new file mode 100644 index 00000000..3cd722ae --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs @@ -0,0 +1,90 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; +using TerraFX.Interop; +using System; + +#pragma warning disable CS0649, IDE1006 + +namespace ABI.Microsoft.Graphics.Canvas; + +/// +/// Raw bindings for the interop interface for the activation factory. +/// +[Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")] +internal unsafe struct ICanvasFactoryNative : IUnknown.Interface +{ + public void** lpVtbl; + + /// + static Guid* INativeGuid.NativeGuid + { + get + { + ReadOnlySpan data = new byte[] { + 0x0D, 0x44, 0x5C, 0x69, + 0xB3, 0x04, + 0xDD, 0x4E, + 0xBF, 0xD9, + 0x63, + 0xE5, + 0x1E, + 0x9F, + 0x72, + 0x02 + }; + + return (Guid*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT QueryInterface(Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged)this.lpVtbl[0])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint AddRef() + { + return ((delegate* unmanaged)this.lpVtbl[1])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public uint Release() + { + return ((delegate* unmanaged)this.lpVtbl[2])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this)); + } + + /// + /// Gets or creates an IInspectable Win2D wrapper for a given native D2D resource. + /// + /// The input canvas device (as a marshalled ). + /// The input native resource to create a wrapper for. + /// The realization DPIs for + /// The resulting wrapper for . + /// The for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public HRESULT GetOrCreate(IUnknown* device, IUnknown* resource, float dpi, void** wrapper) + { + return ((delegate* unmanaged)this.lpVtbl[6])( + (ICanvasFactoryNative*)Unsafe.AsPointer(ref this), + device, + resource, + dpi, + wrapper); + } + + /// + /// The COM import interface for . + /// + [Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")] + [ComImport] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + public interface Interface + { + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs new file mode 100644 index 00000000..442914dc --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs @@ -0,0 +1,184 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using ABI.Microsoft.Graphics.Canvas; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using TerraFX.Interop.WinRT; +using Windows.Graphics.DirectX; +using WinRT; + +namespace ComputeSharp.SwapChain.D2D1.Backend; + +using CanvasDevice = Microsoft.Graphics.Canvas.CanvasDevice; +using CanvasDrawingSession = Microsoft.Graphics.Canvas.CanvasDrawingSession; +using CanvasSwapChain = Microsoft.Graphics.Canvas.CanvasSwapChain; +using Windows = TerraFX.Interop.Windows.Windows; + +/// +/// A simple Win32 application handling a D2D swapchain. +/// +internal sealed class Win32Application +{ + /// + /// The instance to use. + /// + private CanvasDevice? canvasDevice; + + /// + /// The instance to use to render frames. + /// + private CanvasSwapChain? canvasSwapChain; + + /// + /// Whether or not the window has been resized and requires the buffers to be updated. + /// + private bool isResizePending; + + /// + /// Raised whenever a draw operation can be performed. + /// + public event EventHandler? Draw; + + /// + /// Initializes the current application. + /// + /// The handle for the window. + [MemberNotNull(nameof(canvasDevice))] + [MemberNotNull(nameof(canvasSwapChain))] + public unsafe void OnInitialize(HWND hwnd) + { + // Create a new canvas device, which will handle DX11/D2D initialization + CanvasDevice canvasDevice = new(); + CanvasSwapChain canvasSwapChain; + + // Create the swap chain to display frames + using (ComPtr direct3DDeviceUnknown = default) + using (ComPtr dxgiFactory2 = default) + using (ComPtr dxgiSwapChain1 = default) + { + HRESULT hresult; + + // Extract the underlying Direct3D device from the canvas device. + // This is needed for CreateSwapChainForHwnd, as the owning device. + using (ComPtr canvasDeviceUnknown = default) + using (ComPtr direct3DDxgiInterfaceAccess = default) + { + canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable.FromManaged(canvasDevice)); + + hresult = canvasDeviceUnknown.CopyTo(direct3DDxgiInterfaceAccess.GetAddressOf()); + + ExceptionHelpers.ThrowExceptionForHR(hresult); + + hresult = direct3DDxgiInterfaceAccess.Get()->GetInterface(Windows.__uuidof(), (void**)direct3DDeviceUnknown.GetAddressOf()); + + ExceptionHelpers.ThrowExceptionForHR(hresult); + } + + // Create the DXGIFactory2 instance to create the swapchain with + hresult = DirectX.CreateDXGIFactory2(DXGI.DXGI_CREATE_FACTORY_DEBUG, Windows.__uuidof(), (void**)dxgiFactory2.GetAddressOf()); + + ExceptionHelpers.ThrowExceptionForHR(hresult); + + DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default; + dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE; + dxgiSwapChainDesc1.BufferCount = 2; + dxgiSwapChainDesc1.BufferUsage = DXGI.DXGI_USAGE_RENDER_TARGET_OUTPUT; + dxgiSwapChainDesc1.Flags = 0; + dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM; + dxgiSwapChainDesc1.Width = 1; + dxgiSwapChainDesc1.Height = 1; + dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0); + dxgiSwapChainDesc1.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH; + dxgiSwapChainDesc1.Stereo = 0; + dxgiSwapChainDesc1.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; + + // Create the native DXGI swapchain object to wrap + hresult = dxgiFactory2.Get()->CreateSwapChainForHwnd( + direct3DDeviceUnknown.Get(), + hwnd, + &dxgiSwapChainDesc1, + null, + null, + dxgiSwapChain1.GetAddressOf()); + + ExceptionHelpers.ThrowExceptionForHR(hresult); + + using ComPtr canvasFactoryNative = default; + + // Get the activation factory for CanvasDevice + using (ComPtr canvasFactoryNativeUnknown = default) + { + ICanvasFactoryNative.Interface canvasDeviceActivationFactory = CanvasDevice.As(); + + canvasFactoryNativeUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasDeviceActivationFactory)); + + hresult = canvasFactoryNativeUnknown.CopyTo(canvasFactoryNative.GetAddressOf()); + + ExceptionHelpers.ThrowExceptionForHR(hresult); + } + + // Create a Win2D wrapper for the swapchain + using (ComPtr canvasDeviceUnknown = default) + using (ComPtr canvasSwapChainUnknown = default) + { + canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable.FromManaged(canvasDevice)); + + hresult = canvasFactoryNative.Get()->GetOrCreate( + device: canvasDeviceUnknown.Get(), + resource: (IUnknown*)dxgiSwapChain1.Get(), + dpi: 96.0f, + wrapper: (void**)canvasSwapChainUnknown.GetAddressOf()); + + ExceptionHelpers.ThrowExceptionForHR(hresult); + + // Marshal to a WinRT managed object + canvasSwapChain = MarshalInspectable.FromAbi((IntPtr)canvasSwapChainUnknown.Get()); + } + } + + // Save the Win2D objects for later use + this.canvasDevice = canvasDevice; + this.canvasSwapChain = canvasSwapChain; + } + + /// + /// Resizes the current application. + /// + public void OnResize() + { + this.isResizePending = true; + } + + /// + /// Updates the current application. + /// + /// The current time since the start of the application. + public void OnUpdate(TimeSpan time) + { + if (this.isResizePending) + { + // Resize the swapchain if needed (the size is calculated automatically) + this.canvasSwapChain!.ResizeBuffers( + newWidth: 0, + newHeight: 0, + newDpi: 96.0f, + newFormat: DirectXPixelFormat.Unknown, + bufferCount: 0); + + this.isResizePending = false; + } + + // Create the drawing session and invoke all registered draw handler + using (CanvasDrawingSession canvasDrawingSession = this.canvasSwapChain!.CreateDrawingSession(default)) + { + Draw?.Invoke(this, canvasDrawingSession); + } + + // Wait for v-sync + this.canvasSwapChain.WaitForVerticalBlank(); + + // Present the new frame + this.canvasSwapChain.Present(syncInterval: 1); + } +} diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32ApplicationRunner.cs b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32ApplicationRunner.cs new file mode 100644 index 00000000..557cb7e0 --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32ApplicationRunner.cs @@ -0,0 +1,344 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Threading; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.SwapChain.D2D1.Backend; + +using Windows = TerraFX.Interop.Windows.Windows; + +/// +/// A helper class to manage the creation and execution of Win32 applications. +/// +internal static unsafe class Win32ApplicationRunner +{ + /// + /// Whether or not a resize operation is in progress. + /// + private static bool isResizing = false; + + /// + /// Whether or not the application is currently paused. + /// + private static bool isPaused = false; + + /// + /// The for the application window. + /// + private static HWND hwnd; + + /// + /// The application being run. + /// + private static Win32Application application = null!; + + /// + /// The thread running the render loop. + /// + private static Thread renderThread = null!; + + /// + /// Runs a specified application and starts the main loop to update its state. This is the entry point for a given application, + /// and it should be called as soon as the process is launched, excluding any other additional initialization needed. + /// + /// The input application instance to run. + /// Name of the input application instance to run. + /// The title to use for the window being opened. + /// The exit code for the application. + public static int Run(Win32Application application, string applicationName, string windowTitle) + { + Win32ApplicationRunner.application = application; + + HMODULE hInstance = Windows.GetModuleHandleW(null); + + fixed (char* name = applicationName) + fixed (char* title = windowTitle) + { + // Initialize the window class + WNDCLASSEXW windowClassEx = new() + { + cbSize = (uint)sizeof(WNDCLASSEXW), + style = CS.CS_HREDRAW | CS.CS_VREDRAW, + lpfnWndProc = &WindowProc, + hInstance = hInstance, + hCursor = Windows.LoadCursorW(HINSTANCE.NULL, IDC.IDC_ARROW), + lpszClassName = (ushort*)name + }; + + // Register the window class + _ = Windows.RegisterClassExW(&windowClassEx); + + Rectangle windowRect = new(0, 0, 1280, 720); + + // Set the target window size + _ = Windows.AdjustWindowRect((RECT*)&windowRect, WS.WS_OVERLAPPEDWINDOW, Windows.FALSE); + + uint height = (uint)(windowRect.Bottom - windowRect.Top); + uint width = (uint)(windowRect.Right - windowRect.Left); + + // Create the window and store a handle to it + hwnd = Windows.CreateWindowExW( + 0, + windowClassEx.lpszClassName, + (ushort*)title, + WS.WS_OVERLAPPEDWINDOW, + Windows.CW_USEDEFAULT, + Windows.CW_USEDEFAULT, + (int)width, + (int)height, + HWND.NULL, + HMENU.NULL, + hInstance, + (void*)GCHandle.ToIntPtr(GCHandle.Alloc(application)) + ); + + MARGINS margins = default; + margins.cxLeftWidth = -1; + margins.cxRightWidth = -1; + margins.cyTopHeight = -1; + margins.cyBottomHeight = -1; + + _ = Windows.DwmExtendFrameIntoClientArea(hwnd, &margins); + } + + // Initialize the application + application.OnInitialize(hwnd); + + // Display the window + _ = Windows.ShowWindow(hwnd, SW.SW_SHOWDEFAULT); + + MSG msg = default; + + // Setup the render thread that enables smooth resizing of the window + renderThread = new Thread(static args => + { + (Win32Application application, CancellationToken token) = ((Win32Application, CancellationToken))args!; + + Stopwatch stopwatch = Stopwatch.StartNew(); + + while (!token.IsCancellationRequested) + { + application.OnUpdate(stopwatch.Elapsed); + } + }); + + CancellationTokenSource tokenSource = new(); + + renderThread.Start((application, tokenSource.Token)); + + // Process any messages in the queue + while (msg.message != WM.WM_QUIT) + { + if (Windows.PeekMessageW(&msg, HWND.NULL, 0, 0, PM.PM_REMOVE) != 0) + { + _ = Windows.TranslateMessage(&msg); + _ = Windows.DispatchMessageW(&msg); + } + else if (isPaused) + { + Thread.Sleep(100); + } + + // Also listen to Escape and 'Q' to quit + if (msg.message == WM.WM_KEYUP && (msg.wParam == (WPARAM)VK.VK_ESCAPE || msg.wParam == 'Q')) + { + _ = Windows.DestroyWindow(hwnd); + } + } + + tokenSource.Cancel(); + + renderThread.Join(); + + // Return this part of the WM_QUIT message to Windows + return (int)msg.wParam; + } + + /// + /// Processes incoming messages for a window. + /// + /// A handle to the window. + /// The message. + /// Additional message information (the contents depend on the value of ). + /// Additional message information (the contents depend on the value of ). + /// The result of the message processing for the input message. + [UnmanagedCallersOnly] + private static LRESULT WindowProc(HWND hwnd, uint uMsg, WPARAM wParam, LPARAM lParam) + { + switch (uMsg) + { + // Change the paused state on window activation + case WM.WM_ACTIVATE: + { + if (Windows.LOWORD(wParam) == Windows.WA_INACTIVE) + { + isPaused = true; + } + else + { + isPaused = false; + } + + return 0; + } + + // Change the paused state when ESC is pressed + case WM.WM_KEYDOWN: + { + if (wParam == (byte)ConsoleKey.Escape) + { + + if (isPaused) + { + _ = Windows.SetCapture(hwnd); + } + else + { + _ = Windows.ReleaseCapture(); + } + + isPaused = !isPaused; + } + + return 0; + } + + // Window resize started + case WM.WM_ENTERSIZEMOVE: + { + isResizing = true; + + return 0; + } + + // Window resize completed + case WM.WM_EXITSIZEMOVE: + { + isResizing = false; + application.OnResize(); + + return 0; + } + + // Size update + case WM.WM_SIZE: + { + if (!isResizing && wParam != Windows.SIZE_MINIMIZED) + { + application.OnResize(); + } + + return 0; + } + + // Size and position of the window (needed to enable the borderless mode) + case WM.WM_NCCALCSIZE: + { + return 0; + } + + // Enable dragging the window + case WM.WM_NCHITTEST: + { + POINT point; + RECT rect; + + _ = Windows.GetCursorPos(&point); + _ = Windows.GetWindowRect(hwnd, &rect); + + bool isAtTop = Math.Abs(point.y - rect.top) < 12; + bool isAtRight = Math.Abs(point.x - rect.right) < 12; + bool isAtBottom = Math.Abs(point.y - rect.bottom) < 12; + bool isAtLeft = Math.Abs(point.x - rect.left) < 12; + + if (isAtTop) + { + if (isAtRight) + { + return Windows.HTTOPRIGHT; + } + + if (isAtLeft) + { + return Windows.HTTOPLEFT; + } + + return Windows.HTTOP; + } + + if (isAtRight) + { + if (isAtTop) + { + return Windows.HTTOPRIGHT; + } + + if (isAtBottom) + { + return Windows.HTBOTTOMRIGHT; + } + + return Windows.HTRIGHT; + } + + if (isAtBottom) + { + if (isAtRight) + { + return Windows.HTBOTTOMRIGHT; + } + + if (isAtLeft) + { + return Windows.HTBOTTOMLEFT; + } + + return Windows.HTBOTTOM; + } + + if (isAtLeft) + { + if (isAtTop) + { + return Windows.HTTOPLEFT; + } + + if (isAtBottom) + { + return Windows.HTBOTTOMLEFT; + } + + return Windows.HTLEFT; + } + + return Windows.HTCAPTION; + } + + // Restore the drop shadow + case WM.WM_DWMCOMPOSITIONCHANGED: + { + MARGINS margins = default; + margins.cxLeftWidth = -1; + margins.cxRightWidth = -1; + margins.cyTopHeight = -1; + margins.cyBottomHeight = -1; + + _ = Windows.DwmExtendFrameIntoClientArea(hwnd, &margins); + + return 0; + } + + // Shutdown + case WM.WM_DESTROY: + { + Windows.PostQuitMessage(0); + + return 0; + } + } + + return Windows.DefWindowProcW(hwnd, uMsg, wParam, lParam); + } +} \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj index 5811557e..77c27502 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj +++ b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj @@ -2,8 +2,14 @@ Exe - net6.0 + net6.0-windows10.0.22621 x64;ARM64 + $(NoWarn);IDE0065 + + + + + diff --git a/samples/ComputeSharp.SwapChain.D2D1/Program.cs b/samples/ComputeSharp.SwapChain.D2D1/Program.cs new file mode 100644 index 00000000..6d1b619f --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1/Program.cs @@ -0,0 +1,3 @@ +using ComputeSharp.SwapChain.D2D1.Backend; + +return Win32ApplicationRunner.Run(new Win32Application(), "ComputeSharp.SwapChain.D2D1", "test"); \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs b/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs index e6dd3c90..d7445763 100644 --- a/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs +++ b/samples/ComputeSharp.SwapChain/Backend/Win32ApplicationRunner.cs @@ -340,6 +340,7 @@ internal static unsafe class Win32ApplicationRunner case WM.WM_DESTROY: { Windows.PostQuitMessage(0); + return 0; } }