From 1bd588500e782e74d2095d21614839e93ed66bf3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 15 Apr 2023 18:22:27 +0200 Subject: [PATCH 01/10] Add blank D2D sample with WASDK --- ComputeSharp.sln | 11 +++++++++++ .../ComputeSharp.SwapChain.D2D1.csproj | 9 +++++++++ 2 files changed, 20 insertions(+) create mode 100644 samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 7b49c5d0..55cdf7ce 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -153,6 +153,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{B54B6DCA tests\Directory.Build.targets = tests\Directory.Build.targets EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.SwapChain.D2D1", "samples\ComputeSharp.SwapChain.D2D1\ComputeSharp.SwapChain.D2D1.csproj", "{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -409,6 +411,14 @@ Global {BD9E6556-357E-4C20-BFCD-FB131F9372FA}.Release|ARM64.Build.0 = Release|ARM64 {BD9E6556-357E-4C20-BFCD-FB131F9372FA}.Release|x64.ActiveCfg = Release|x64 {BD9E6556-357E-4C20-BFCD-FB131F9372FA}.Release|x64.Build.0 = Release|x64 + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Debug|ARM64.Build.0 = Debug|ARM64 + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Debug|x64.ActiveCfg = Debug|x64 + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Debug|x64.Build.0 = Debug|x64 + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|ARM64.ActiveCfg = Release|ARM64 + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|ARM64.Build.0 = Release|ARM64 + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|x64.ActiveCfg = Release|x64 + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -445,6 +455,7 @@ Global {F8BF7666-7CCF-4FE4-B055-2EBA4BCD4564} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} {568E7009-5C13-4153-9C94-0AC7A3E6883C} = {1A9C4108-F61A-4ABE-B5CF-F524521EAE2D} {B54B6DCA-6EAB-46A8-83D3-15154659F47F} = {1A9C4108-F61A-4ABE-B5CF-F524521EAE2D} + {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} diff --git a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj new file mode 100644 index 00000000..5811557e --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj @@ -0,0 +1,9 @@ + + + + Exe + net6.0 + x64;ARM64 + + + From 6b330d1973d56b4623d55e0819ef6e94a52fcbe6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 15 Apr 2023 18:42:01 +0200 Subject: [PATCH 02/10] 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; } } From f6388dcd150b5caa843340753ce8fe2cb2fc7043 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 15 Apr 2023 19:34:33 +0200 Subject: [PATCH 03/10] Implement D2D1 drawing in new WASDK sample --- ComputeSharp.sln | 3 +- .../ICanvasFactoryNative.cs | 2 +- .../Backend/PixelShaderEffect.cs | 115 ++++++++++++++++++ .../Backend/Win32Application.cs | 20 ++- .../ComputeSharp.SwapChain.D2D1.csproj | 11 ++ .../ComputeSharp.SwapChain.D2D1/Program.cs | 73 ++++++++++- 6 files changed, 219 insertions(+), 5 deletions(-) create mode 100644 samples/ComputeSharp.SwapChain.D2D1/Backend/PixelShaderEffect.cs diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 55cdf7ce..3d05bd7f 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -153,7 +153,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{B54B6DCA tests\Directory.Build.targets = tests\Directory.Build.targets EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.SwapChain.D2D1", "samples\ComputeSharp.SwapChain.D2D1\ComputeSharp.SwapChain.D2D1.csproj", "{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SwapChain.D2D1", "samples\ComputeSharp.SwapChain.D2D1\ComputeSharp.SwapChain.D2D1.csproj", "{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -478,6 +478,7 @@ Global src\ComputeSharp.D2D1.UI\ComputeSharp.D2D1.UI.projitems*{902d7b44-2c6c-4fcd-840b-ebcae811ee63}*SharedItemsImports = 13 src\ComputeSharp.SourceGeneration.Hlsl\ComputeSharp.SourceGeneration.Hlsl.projitems*{9ac496a3-bbf0-4c8f-a50d-a20bf01c5e05}*SharedItemsImports = 13 src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{9da1da9f-f8b2-4b25-be80-c21f773029e3}*SharedItemsImports = 13 + samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{9ea5ae9d-c39a-4f43-b03e-0a848ea2558a}*SharedItemsImports = 5 src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{a5997814-d8d2-4541-87ac-c3e53caa67c0}*SharedItemsImports = 13 src\ComputeSharp.UI\ComputeSharp.UI.projitems*{afaafdc9-be42-45d4-8c79-0ee8c8edbf52}*SharedItemsImports = 5 src\ComputeSharp.D2D1.UI\ComputeSharp.D2D1.UI.projitems*{bd9e6556-357e-4c20-bfcd-fb131f9372fa}*SharedItemsImports = 5 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 index 3cd722ae..ba7a363a 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs @@ -66,7 +66,7 @@ internal unsafe struct ICanvasFactoryNative : IUnknown.Interface /// The input native resource to create a wrapper for. /// The realization DPIs for /// The resulting wrapper for . - /// The for the operation. + /// The HRESULT for the operation. [MethodImpl(MethodImplOptions.AggressiveInlining)] public HRESULT GetOrCreate(IUnknown* device, IUnknown* resource, float dpi, void** wrapper) { diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/PixelShaderEffect.cs b/samples/ComputeSharp.SwapChain.D2D1/Backend/PixelShaderEffect.cs new file mode 100644 index 00000000..44175d6a --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/PixelShaderEffect.cs @@ -0,0 +1,115 @@ +using System; +using ComputeSharp.D2D1; +using ComputeSharp.D2D1.WinUI; +using Microsoft.Graphics.Canvas; + +namespace ComputeSharp.SwapChain.D2D1.Backend; + +/// +/// An base effect for an animated pixel shader. +/// +internal abstract class PixelShaderEffect : CanvasEffect +{ + /// + /// The current elapsed time. + /// + private TimeSpan elapsedTime; + + /// + /// The current screen width in raw pixels. + /// + private int screenWidth; + + /// + /// The current screen height in raw pixels. + /// + private int screenHeight; + + /// + /// Gets or sets the total elapsed time. + /// + public TimeSpan ElapsedTime + { + get => this.elapsedTime; + set => SetAndInvalidateEffectGraph(ref this.elapsedTime, value); + } + + /// + /// Gets or sets the screen width in raw pixels. + /// + public int ScreenWidth + { + get => this.screenWidth; + set => SetAndInvalidateEffectGraph(ref this.screenWidth, value); + } + + /// + /// Gets or sets the screen height in raw pixels. + /// + public int ScreenHeight + { + get => this.screenHeight; + set => SetAndInvalidateEffectGraph(ref this.screenHeight, value); + } + + /// + /// An effect for an animated pixel shader. + /// + /// The type of pixel shader to render. + public sealed class For : PixelShaderEffect + where T : unmanaged, ID2D1PixelShader + { + /// + /// The factory to use. + /// + private readonly Factory factory; + + /// + /// The instance in use. + /// + private PixelShaderEffect? effect; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The input factory. + public For(Factory factory) + { + this.factory = factory; + } + + /// + protected override ICanvasImage BuildEffectGraph() + { + this.effect = new PixelShaderEffect(); + + return this.effect; + } + + /// + protected override void ConfigureEffectGraph() + { + this.effect!.ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight); + } + + /// + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (disposing) + { + this.effect?.Dispose(); + } + } + + /// + /// A factory of a given shader instance. + /// + /// The total elapsed time. + /// The screen width in raw pixels. + /// The screen height in raw pixels. + /// A shader instance to render. + public delegate T Factory(TimeSpan elapsedTime, int screenWidth, int screenHeight); + } +} diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs index 442914dc..99459482 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs @@ -38,7 +38,7 @@ internal sealed class Win32Application /// /// Raised whenever a draw operation can be performed. /// - public event EventHandler? Draw; + public event EventHandler? Draw; /// /// Initializes the current application. @@ -172,7 +172,7 @@ internal sealed class Win32Application // Create the drawing session and invoke all registered draw handler using (CanvasDrawingSession canvasDrawingSession = this.canvasSwapChain!.CreateDrawingSession(default)) { - Draw?.Invoke(this, canvasDrawingSession); + Draw?.Invoke(this, new DrawEventArgs { TotalTime = time, DrawingSession = canvasDrawingSession }); } // Wait for v-sync @@ -181,4 +181,20 @@ internal sealed class Win32Application // Present the new frame this.canvasSwapChain.Present(syncInterval: 1); } + + /// + /// Arguments for . + /// + public sealed class DrawEventArgs : EventArgs + { + /// + /// Gets the total time for the rendering loop. + /// + public required TimeSpan TotalTime { get; init; } + + /// + /// Gets the instance to use. + /// + public required CanvasDrawingSession DrawingSession { get; init; } + } } diff --git a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj index 77c27502..6eb5e77e 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj +++ b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj @@ -9,7 +9,18 @@ + + + + + + + + + + + diff --git a/samples/ComputeSharp.SwapChain.D2D1/Program.cs b/samples/ComputeSharp.SwapChain.D2D1/Program.cs index 6d1b619f..0b06db95 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/Program.cs +++ b/samples/ComputeSharp.SwapChain.D2D1/Program.cs @@ -1,3 +1,74 @@ +using System; using ComputeSharp.SwapChain.D2D1.Backend; +using ComputeSharp.SwapChain.Shaders.D2D1; -return Win32ApplicationRunner.Run(new Win32Application(), "ComputeSharp.SwapChain.D2D1", "test"); \ No newline at end of file +namespace ComputeSharp.SwapChain; + +class Program +{ + /// + /// The mapping of available samples to choose from. + /// + private static readonly (string ShaderName, PixelShaderEffect Effect)[] Samples = new (string, PixelShaderEffect)[] + { + (nameof(HelloWorld), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(ColorfulInfinity), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(FractalTiling), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(TwoTiledTruchet), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(MengerJourney), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(Octagrams), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(ProteanClouds), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(PyramidPattern), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(TriangleGridContouring), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), + (nameof(TerracedHills), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))) + }; + + static void Main() + { + int index; + + do + { + Console.Clear(); + Console.WriteLine("Available samples:"); + Console.WriteLine(); + + for (int i = 0; i < Samples.Length; i++) + { + Console.WriteLine($"{i}: {Samples[i].ShaderName}"); + } + + Console.WriteLine($"{Samples.Length}+: Exit (Use Escape, 'Q', or Alt + F4 to exit a sample once chosen)"); + Console.WriteLine(); + + do + { + Console.Write("Enter the index of the sample to run: "); + } + while (!int.TryParse(Console.ReadLine(), out index)); + + if (index >= 0 && index < Samples.Length) + { + Console.WriteLine(); + Console.WriteLine($"Starting {Samples[index].ShaderName}..."); + + Win32Application win32Application = new(); + PixelShaderEffect effect = Samples[index].Effect; + + win32Application.Draw += (_, e) => + { + // Set the effect properties + effect.ElapsedTime = e.TotalTime; + effect.ScreenWidth = 1280; + effect.ScreenHeight = 720; + + // Draw the effect + e.DrawingSession.DrawImage(effect); + }; + + _ = Win32ApplicationRunner.Run(win32Application, "ComputeSharp.SwapChain.D2D1", Samples[index].ShaderName); + } + } + while (index >= 0 && index < Samples.Length); + } +} \ No newline at end of file From 09c0c1e8743846dd1f886cfe68620fe3f7d4ae78 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 15 Apr 2023 19:40:50 +0200 Subject: [PATCH 04/10] Handle size changes when drawing frames --- .../Backend/Win32Application.cs | 40 +++++++++++++++++-- .../ComputeSharp.SwapChain.D2D1/Program.cs | 4 +- .../Backend/SwapChainApplication{T}.cs | 2 +- 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs index 99459482..c100ad18 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs @@ -6,6 +6,7 @@ using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using TerraFX.Interop.WinRT; using Windows.Graphics.DirectX; +using Windows.Graphics.Imaging; using WinRT; namespace ComputeSharp.SwapChain.D2D1.Backend; @@ -33,7 +34,17 @@ internal sealed class Win32Application /// /// Whether or not the window has been resized and requires the buffers to be updated. /// - private bool isResizePending; + private volatile bool isResizePending; + + /// + /// The current screen width in raw pixels. + /// + private uint screenWidth; + + /// + /// The current screen height in raw pixels. + /// + private uint screenHeight; /// /// Raised whenever a draw operation can be performed. @@ -86,8 +97,8 @@ internal sealed class Win32Application 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.Width = this.screenWidth = 1; + dxgiSwapChainDesc1.Height = this.screenHeight = 1; dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0); dxgiSwapChainDesc1.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH; dxgiSwapChainDesc1.Stereo = 0; @@ -166,13 +177,24 @@ internal sealed class Win32Application newFormat: DirectXPixelFormat.Unknown, bufferCount: 0); + BitmapSize bitmapSize = this.canvasSwapChain!.SizeInPixels; + + this.screenWidth = bitmapSize.Width; + this.screenHeight = bitmapSize.Height; + this.isResizePending = false; } // Create the drawing session and invoke all registered draw handler using (CanvasDrawingSession canvasDrawingSession = this.canvasSwapChain!.CreateDrawingSession(default)) { - Draw?.Invoke(this, new DrawEventArgs { TotalTime = time, DrawingSession = canvasDrawingSession }); + Draw?.Invoke(this, new DrawEventArgs + { + ScreenWidth = this.screenWidth, + ScreenHeight = this.screenHeight, + TotalTime = time, + DrawingSession = canvasDrawingSession + }); } // Wait for v-sync @@ -187,6 +209,16 @@ internal sealed class Win32Application /// public sealed class DrawEventArgs : EventArgs { + /// + /// Gets the screen width in raw pixels. + /// + public required uint ScreenWidth { get; init; } + + /// + /// Gets the screen height in raw pixels. + /// + public required uint ScreenHeight { get; init; } + /// /// Gets the total time for the rendering loop. /// diff --git a/samples/ComputeSharp.SwapChain.D2D1/Program.cs b/samples/ComputeSharp.SwapChain.D2D1/Program.cs index 0b06db95..7da94709 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/Program.cs +++ b/samples/ComputeSharp.SwapChain.D2D1/Program.cs @@ -59,8 +59,8 @@ class Program { // Set the effect properties effect.ElapsedTime = e.TotalTime; - effect.ScreenWidth = 1280; - effect.ScreenHeight = 720; + effect.ScreenWidth = (int)e.ScreenWidth; + effect.ScreenHeight = (int)e.ScreenHeight; // Draw the effect e.DrawingSession.DrawImage(effect); diff --git a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs index 41713dbe..d4d15aec 100644 --- a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs +++ b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs @@ -71,7 +71,7 @@ internal sealed class SwapChainApplication : Win32Application /// /// Whether or not the window has been resized and requires the buffers to be updated. /// - private bool isResizePending; + private volatile bool isResizePending; /// /// Creates a new instance with the specified parameters. From c86b198b467ff4ebf5329d49b53a9604163b43ee Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 16 Apr 2023 18:09:35 +0200 Subject: [PATCH 05/10] Stop using built-in COM interop in D2D1 sample --- .../ICanvasFactoryNative.cs | 21 +++++++++++++++---- .../Backend/Win32Application.cs | 3 +-- 2 files changed, 18 insertions(+), 6 deletions(-) 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 index ba7a363a..c5bd740f 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs @@ -1,8 +1,10 @@ +using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TerraFX.Interop.Windows; using TerraFX.Interop; -using System; +using WinRT; +using WinRT.Interop; #pragma warning disable CS0649, IDE1006 @@ -79,12 +81,23 @@ internal unsafe struct ICanvasFactoryNative : IUnknown.Interface } /// - /// The COM import interface for . + /// The managed interface for . /// [Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")] - [ComImport] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + [WindowsRuntimeType] + [WindowsRuntimeHelperType(typeof(Interface))] public interface Interface { + /// + /// The vtable type for . + /// + [Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")] + public readonly struct Vftbl + { + /// + /// Allows CsWinRT to retrieve a pointer to the projection vtable (the name is hardcoded by convention). + /// + public static readonly IntPtr AbiToProjectionVftablePtr = IUnknownVftbl.AbiToProjectionVftblPtr; + } } } \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs index c100ad18..18378ed5 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs +++ b/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs @@ -1,6 +1,5 @@ using System; using System.Diagnostics.CodeAnalysis; -using System.Runtime.InteropServices; using ABI.Microsoft.Graphics.Canvas; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -122,7 +121,7 @@ internal sealed class Win32Application { ICanvasFactoryNative.Interface canvasDeviceActivationFactory = CanvasDevice.As(); - canvasFactoryNativeUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasDeviceActivationFactory)); + canvasFactoryNativeUnknown.Attach((IUnknown*)MarshalInterface.FromManaged(canvasDeviceActivationFactory)); hresult = canvasFactoryNativeUnknown.CopyTo(canvasFactoryNative.GetAddressOf()); From 699d905234c2220ef372b561da5ee87f9fd50447 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 18 Apr 2023 01:02:26 +0200 Subject: [PATCH 06/10] Add manifest for DPI awareness to D2D WASDK sample --- .../ComputeSharp.SwapChain.D2D1.csproj | 1 + samples/ComputeSharp.SwapChain.D2D1/app.manifest | 9 +++++++++ 2 files changed, 10 insertions(+) create mode 100644 samples/ComputeSharp.SwapChain.D2D1/app.manifest diff --git a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj index 6eb5e77e..e7b44c1a 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj +++ b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj @@ -3,6 +3,7 @@ Exe net6.0-windows10.0.22621 + app.manifest x64;ARM64 $(NoWarn);IDE0065 diff --git a/samples/ComputeSharp.SwapChain.D2D1/app.manifest b/samples/ComputeSharp.SwapChain.D2D1/app.manifest new file mode 100644 index 00000000..526a6e63 --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1/app.manifest @@ -0,0 +1,9 @@ + + + + + true + PerMonitorV2 + + + From 2f72522bc3828530dbbb1d99f4d433117da59d1b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 17 Apr 2023 01:45:00 +0200 Subject: [PATCH 07/10] Add .rd.xml file to D2D1 sample, improve .csproj --- .../ComputeSharp.SwapChain.D2D1.csproj | 15 ++++++++++++++- .../Properties/Default.rd.xml | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 samples/ComputeSharp.SwapChain.D2D1/Properties/Default.rd.xml diff --git a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj index e7b44c1a..570bdc08 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj +++ b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj @@ -2,12 +2,25 @@ Exe - net6.0-windows10.0.22621 + net7.0-windows10.0.22621 app.manifest x64;ARM64 $(NoWarn);IDE0065 + + + true + true + true + Speed + + + + + + + diff --git a/samples/ComputeSharp.SwapChain.D2D1/Properties/Default.rd.xml b/samples/ComputeSharp.SwapChain.D2D1/Properties/Default.rd.xml new file mode 100644 index 00000000..95116ed6 --- /dev/null +++ b/samples/ComputeSharp.SwapChain.D2D1/Properties/Default.rd.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file From 27e7b0fa94d4b898f71e60a37ffbdc2a6af192b3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 21 Apr 2023 13:01:44 +0200 Subject: [PATCH 08/10] Switch Win2D WASDK sample to CLI style --- .../ComputeSharp.SwapChain.D2D1.csproj | 4 +- .../ComputeSharp.SwapChain.D2D1/Program.cs | 120 +++++++++--------- 2 files changed, 62 insertions(+), 62 deletions(-) diff --git a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj index 570bdc08..6a8139da 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj +++ b/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj @@ -1,7 +1,8 @@ - Exe + Exe + WinExe net7.0-windows10.0.22621 app.manifest x64;ARM64 @@ -22,7 +23,6 @@ - diff --git a/samples/ComputeSharp.SwapChain.D2D1/Program.cs b/samples/ComputeSharp.SwapChain.D2D1/Program.cs index 7da94709..25467b03 100644 --- a/samples/ComputeSharp.SwapChain.D2D1/Program.cs +++ b/samples/ComputeSharp.SwapChain.D2D1/Program.cs @@ -1,74 +1,74 @@ using System; using ComputeSharp.SwapChain.D2D1.Backend; using ComputeSharp.SwapChain.Shaders.D2D1; +using TerraFX.Interop.Windows; -namespace ComputeSharp.SwapChain; - -class Program +// Accepted inputs: +// - [] +// - [] +if (args is [] or [_]) { - /// - /// The mapping of available samples to choose from. - /// - private static readonly (string ShaderName, PixelShaderEffect Effect)[] Samples = new (string, PixelShaderEffect)[] + // If there are no args, just run the default shader + if (args is not [string shaderName]) { - (nameof(HelloWorld), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(ColorfulInfinity), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(FractalTiling), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(TwoTiledTruchet), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(MengerJourney), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(Octagrams), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(ProteanClouds), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(PyramidPattern), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(TriangleGridContouring), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))), - (nameof(TerracedHills), new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)))) + shaderName = nameof(ColorfulInfinity); + } + + // Get the requested shader, if possible + PixelShaderEffect? effect = shaderName.ToLowerInvariant() switch + { + "helloworld" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "colorfulinfinity" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "fractaltiling" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "twotiledtruchet" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "mengerjourney" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "octagrams" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "proteanclouds" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "pyramidpattern" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "trianglegridcontouring" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + "terracedhills" => new PixelShaderEffect.For(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))), + _ => null }; - static void Main() + // If a shader is found, run it + if (effect is not null) { - int index; + Win32Application win32Application = new(); - do + win32Application.Draw += (_, e) => { - Console.Clear(); - Console.WriteLine("Available samples:"); - Console.WriteLine(); + // Set the effect properties + effect.ElapsedTime = e.TotalTime; + effect.ScreenWidth = (int)e.ScreenWidth; + effect.ScreenHeight = (int)e.ScreenHeight; - for (int i = 0; i < Samples.Length; i++) - { - Console.WriteLine($"{i}: {Samples[i].ShaderName}"); - } + // Draw the effect + e.DrawingSession.DrawImage(effect); + }; - Console.WriteLine($"{Samples.Length}+: Exit (Use Escape, 'Q', or Alt + F4 to exit a sample once chosen)"); - Console.WriteLine(); - - do - { - Console.Write("Enter the index of the sample to run: "); - } - while (!int.TryParse(Console.ReadLine(), out index)); - - if (index >= 0 && index < Samples.Length) - { - Console.WriteLine(); - Console.WriteLine($"Starting {Samples[index].ShaderName}..."); - - Win32Application win32Application = new(); - PixelShaderEffect effect = Samples[index].Effect; - - win32Application.Draw += (_, e) => - { - // Set the effect properties - effect.ElapsedTime = e.TotalTime; - effect.ScreenWidth = (int)e.ScreenWidth; - effect.ScreenHeight = (int)e.ScreenHeight; - - // Draw the effect - e.DrawingSession.DrawImage(effect); - }; - - _ = Win32ApplicationRunner.Run(win32Application, "ComputeSharp.SwapChain.D2D1", Samples[index].ShaderName); - } - } - while (index >= 0 && index < Samples.Length); + return Win32ApplicationRunner.Run(win32Application, "ComputeSharp.D2D1", "ComputeSharp.D2D1"); } -} \ No newline at end of file + + // If no shader matches, check if help was requested + if (shaderName is "-h") + { + Console.WriteLine($""" + Available shaders: + + - {nameof(HelloWorld)} + - {nameof(ColorfulInfinity)} + - {nameof(FractalTiling)} + - {nameof(TwoTiledTruchet)} + - {nameof(MengerJourney)} + - {nameof(Octagrams)} + - {nameof(ProteanClouds)} + - {nameof(PyramidPattern)} + - {nameof(TriangleGridContouring)} + - {nameof(TerracedHills)} + """); + + return S.S_OK; + } +} + +return E.E_INVALIDARG; \ No newline at end of file From bdc3679e56aae27631b0206ece64e08b2cc6d842 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 21 Apr 2023 13:04:30 +0200 Subject: [PATCH 09/10] Rename Win2D WASDK sample to use CLI suffix --- ComputeSharp.sln | 5 ++--- .../ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs | 0 .../Backend/PixelShaderEffect.cs | 0 .../Backend/Win32Application.cs | 0 .../Backend/Win32ApplicationRunner.cs | 0 .../ComputeSharp.SwapChain.D2D1.Cli.csproj} | 0 .../Program.cs | 0 .../Properties/Default.rd.xml | 0 .../app.manifest | 0 9 files changed, 2 insertions(+), 3 deletions(-) rename samples/{ComputeSharp.SwapChain.D2D1 => ComputeSharp.SwapChain.D2D1.Cli}/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs (100%) rename samples/{ComputeSharp.SwapChain.D2D1 => ComputeSharp.SwapChain.D2D1.Cli}/Backend/PixelShaderEffect.cs (100%) rename samples/{ComputeSharp.SwapChain.D2D1 => ComputeSharp.SwapChain.D2D1.Cli}/Backend/Win32Application.cs (100%) rename samples/{ComputeSharp.SwapChain.D2D1 => ComputeSharp.SwapChain.D2D1.Cli}/Backend/Win32ApplicationRunner.cs (100%) rename samples/{ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj => ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj} (100%) rename samples/{ComputeSharp.SwapChain.D2D1 => ComputeSharp.SwapChain.D2D1.Cli}/Program.cs (100%) rename samples/{ComputeSharp.SwapChain.D2D1 => ComputeSharp.SwapChain.D2D1.Cli}/Properties/Default.rd.xml (100%) rename samples/{ComputeSharp.SwapChain.D2D1 => ComputeSharp.SwapChain.D2D1.Cli}/app.manifest (100%) diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 3d05bd7f..37e36f64 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -1,5 +1,4 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31825.309 MinimumVisualStudioVersion = 10.0.40219.1 @@ -153,7 +152,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{B54B6DCA tests\Directory.Build.targets = tests\Directory.Build.targets EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SwapChain.D2D1", "samples\ComputeSharp.SwapChain.D2D1\ComputeSharp.SwapChain.D2D1.csproj", "{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.SwapChain.D2D1.Cli", "samples\ComputeSharp.SwapChain.D2D1.Cli\ComputeSharp.SwapChain.D2D1.Cli.csproj", "{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs similarity index 100% rename from samples/ComputeSharp.SwapChain.D2D1/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs rename to samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/ABI.Microsoft.Graphics.Canvas/ICanvasFactoryNative.cs diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/PixelShaderEffect.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs similarity index 100% rename from samples/ComputeSharp.SwapChain.D2D1/Backend/PixelShaderEffect.cs rename to samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32Application.cs similarity index 100% rename from samples/ComputeSharp.SwapChain.D2D1/Backend/Win32Application.cs rename to samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32Application.cs diff --git a/samples/ComputeSharp.SwapChain.D2D1/Backend/Win32ApplicationRunner.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32ApplicationRunner.cs similarity index 100% rename from samples/ComputeSharp.SwapChain.D2D1/Backend/Win32ApplicationRunner.cs rename to samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/Win32ApplicationRunner.cs diff --git a/samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj b/samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj similarity index 100% rename from samples/ComputeSharp.SwapChain.D2D1/ComputeSharp.SwapChain.D2D1.csproj rename to samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj diff --git a/samples/ComputeSharp.SwapChain.D2D1/Program.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs similarity index 100% rename from samples/ComputeSharp.SwapChain.D2D1/Program.cs rename to samples/ComputeSharp.SwapChain.D2D1.Cli/Program.cs diff --git a/samples/ComputeSharp.SwapChain.D2D1/Properties/Default.rd.xml b/samples/ComputeSharp.SwapChain.D2D1.Cli/Properties/Default.rd.xml similarity index 100% rename from samples/ComputeSharp.SwapChain.D2D1/Properties/Default.rd.xml rename to samples/ComputeSharp.SwapChain.D2D1.Cli/Properties/Default.rd.xml diff --git a/samples/ComputeSharp.SwapChain.D2D1/app.manifest b/samples/ComputeSharp.SwapChain.D2D1.Cli/app.manifest similarity index 100% rename from samples/ComputeSharp.SwapChain.D2D1/app.manifest rename to samples/ComputeSharp.SwapChain.D2D1.Cli/app.manifest From 6820ec181d0d016440d1d8584a94b69f8c39cb2d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 21 Apr 2023 13:25:25 +0200 Subject: [PATCH 10/10] Add Win2D WASDK sample to CI tests --- .github/workflows/dotnet.yml | 19 ++++++++++++++++++- .../ComputeSharp.SwapChain.D2D1.Cli.csproj | 8 ++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index eaa46939..d1b18b54 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -134,6 +134,8 @@ jobs: steps: - name: Git checkout uses: actions/checkout@v3 + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.1 - name: Build and run ComputeSharp.Sample run: > dotnet build samples\ComputeSharp.Sample\ComputeSharp.Sample.csproj -c Release -f ${{matrix.framework}} -r win-x64 --no-self-contained -p:Platform=x64 -v n; @@ -147,7 +149,7 @@ jobs: dotnet build samples\ComputeSharp.ImageProcessing\ComputeSharp.ImageProcessing.csproj -c Release -f ${{matrix.framework}} -r win-x64 --no-self-contained -p:Platform=x64 -v n; samples\ComputeSharp.ImageProcessing\bin\x64\Release\${{matrix.framework}}\win-x64\ComputeSharp.ImageProcessing.exe - # Also publish the NativeAOT test when .NET 7 is used + # Publish the NativeAOT test when .NET 7 is used - if: matrix.framework == 'net7.0' name: Publish ComputeSharp.SwapChain.Cli with NativeAOT run: > @@ -169,6 +171,21 @@ jobs: path: samples\ComputeSharp.SwapChain.Cli\bin\Release\net7.0\win-x64\publish\computesharp.cli.exe if-no-files-found: error + # Also publish the Win2D sample on .NET 7 (without NativeAOT, see https://github.com/dotnet/runtime/issues/84908) + - if: matrix.framework == 'net7.0' + name: Publish ComputeSharp.SwapChain.D2D1.Cli + run: > + msbuild samples\ComputeSharp.SwapChain.D2D1.Cli\ComputeSharp.SwapChain.D2D1.Cli.csproj -t:restore,publish /p:Configuration=Release + /p:Platform=x64 /p:RuntimeIdentifier=win10-x64 /p:PublishSingleFile=True /p:SelfContained=True /p:PublishTrimmed=True + - if: matrix.framework == 'net7.0' + name: Run ComputeSharp.SwapChain.D2D1.Cli + run: > + $process = (Start-Process samples\ComputeSharp.SwapChain.D2D1.Cli\bin\x64\Release\net7.0-windows10.0.22621\win10-x64\publish\computesharp.d2d1.cli.exe -PassThru); + sleep -Seconds 2; + $process.CloseMainWindow() | Out-Null; + $process.WaitForExit(); + $process.ExitCode + # Download the NuGet packages generated in the previous job and use them # to build and run the sample project referencing them. This is used as # a test to ensure the NuGet packages work in a consuming project. diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj b/samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj index 6a8139da..5e9b56f4 100644 --- a/samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj +++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/ComputeSharp.SwapChain.D2D1.Cli.csproj @@ -7,6 +7,14 @@ app.manifest x64;ARM64 $(NoWarn);IDE0065 + computesharp.d2d1.cli + ..\ComputeSharp.SwapChain.Cli\icon.ico + + + + + + $(NoWarn);IL2104;IL2026