Merge pull request #509 from Sergio0694/dev/win2d-wasdk-sample

Add unpackaged Win2D WASDK Win32 CLI sample
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-04-21 17:14:02 -07:00
コミット 06c33ba6ae
12ファイル変更
+972 -4

検索条件に一致するファイルはありません

+18 -1
ファイルの表示
@@ -134,6 +134,8 @@ jobs:
steps:
- name: Git checkout
uses: actions/checkout@v3
- name: Add msbuild to PATH
uses: microsoft/[email protected]
- 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.
+13 -2
ファイルの表示
@@ -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,6 +152,8 @@ 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.Cli", "samples\ComputeSharp.SwapChain.D2D1.Cli\ComputeSharp.SwapChain.D2D1.Cli.csproj", "{9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -409,6 +410,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 +454,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}
@@ -467,6 +477,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
@@ -0,0 +1,103 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
using TerraFX.Interop;
using WinRT;
using WinRT.Interop;
#pragma warning disable CS0649, IDE1006
namespace ABI.Microsoft.Graphics.Canvas;
/// <summary>
/// Raw bindings for the interop interface for the <see cref="CanvasDevice"/> activation factory.
/// </summary>
[Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")]
internal unsafe struct ICanvasFactoryNative : IUnknown.Interface
{
public void** lpVtbl;
/// <inheritdoc/>
static Guid* INativeGuid.NativeGuid
{
get
{
ReadOnlySpan<byte> 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));
}
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT QueryInterface(Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<ICanvasFactoryNative*, Guid*, void**, int>)this.lpVtbl[0])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint AddRef()
{
return ((delegate* unmanaged<ICanvasFactoryNative*, uint>)this.lpVtbl[1])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this));
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint Release()
{
return ((delegate* unmanaged<ICanvasFactoryNative*, uint>)this.lpVtbl[2])((ICanvasFactoryNative*)Unsafe.AsPointer(ref this));
}
/// <summary>
/// Gets or creates an <c>IInspectable</c> Win2D wrapper for a given native D2D resource.
/// </summary>
/// <param name="device">The input canvas device (as a marshalled <see cref="global::Microsoft.Graphics.Canvas.CanvasDevice"/>).</param>
/// <param name="resource">The input native resource to create a wrapper for.</param>
/// <param name="dpi">The realization DPIs for <paramref name="resource"/></param>
/// <param name="wrapper">The resulting wrapper for <paramref name="resource"/>.</param>
/// <returns>The <c>HRESULT</c> for the operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public HRESULT GetOrCreate(IUnknown* device, IUnknown* resource, float dpi, void** wrapper)
{
return ((delegate* unmanaged<ICanvasFactoryNative*, IUnknown*, IUnknown*, float, void**, int>)this.lpVtbl[6])(
(ICanvasFactoryNative*)Unsafe.AsPointer(ref this),
device,
resource,
dpi,
wrapper);
}
/// <summary>
/// The managed interface for <see cref="ICanvasFactoryNative"/>.
/// </summary>
[Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")]
[WindowsRuntimeType]
[WindowsRuntimeHelperType(typeof(Interface))]
public interface Interface
{
/// <summary>
/// The vtable type for <see cref="Interface"/>.
/// </summary>
[Guid("695C440D-04B3-4EDD-BFD9-63E51E9F7202")]
public readonly struct Vftbl
{
/// <summary>
/// Allows CsWinRT to retrieve a pointer to the projection vtable (the name is hardcoded by convention).
/// </summary>
public static readonly IntPtr AbiToProjectionVftablePtr = IUnknownVftbl.AbiToProjectionVftblPtr;
}
}
}
+115
ファイルの表示
@@ -0,0 +1,115 @@
using System;
using ComputeSharp.D2D1;
using ComputeSharp.D2D1.WinUI;
using Microsoft.Graphics.Canvas;
namespace ComputeSharp.SwapChain.D2D1.Backend;
/// <summary>
/// An base effect for an animated pixel shader.
/// </summary>
internal abstract class PixelShaderEffect : CanvasEffect
{
/// <summary>
/// The current elapsed time.
/// </summary>
private TimeSpan elapsedTime;
/// <summary>
/// The current screen width in raw pixels.
/// </summary>
private int screenWidth;
/// <summary>
/// The current screen height in raw pixels.
/// </summary>
private int screenHeight;
/// <summary>
/// Gets or sets the total elapsed time.
/// </summary>
public TimeSpan ElapsedTime
{
get => this.elapsedTime;
set => SetAndInvalidateEffectGraph(ref this.elapsedTime, value);
}
/// <summary>
/// Gets or sets the screen width in raw pixels.
/// </summary>
public int ScreenWidth
{
get => this.screenWidth;
set => SetAndInvalidateEffectGraph(ref this.screenWidth, value);
}
/// <summary>
/// Gets or sets the screen height in raw pixels.
/// </summary>
public int ScreenHeight
{
get => this.screenHeight;
set => SetAndInvalidateEffectGraph(ref this.screenHeight, value);
}
/// <summary>
/// An effect for an animated pixel shader.
/// </summary>
/// <typeparam name="T">The type of pixel shader to render.</typeparam>
public sealed class For<T> : PixelShaderEffect
where T : unmanaged, ID2D1PixelShader
{
/// <summary>
/// The <typeparamref name="T"/> factory to use.
/// </summary>
private readonly Factory factory;
/// <summary>
/// The <see cref="PixelShaderEffect{T}"/> instance in use.
/// </summary>
private PixelShaderEffect<T>? effect;
/// <summary>
/// Creates a new <see cref="For{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="factory">The input <typeparamref name="T"/> factory.</param>
public For(Factory factory)
{
this.factory = factory;
}
/// <inheritdoc/>
protected override ICanvasImage BuildEffectGraph()
{
this.effect = new PixelShaderEffect<T>();
return this.effect;
}
/// <inheritdoc/>
protected override void ConfigureEffectGraph()
{
this.effect!.ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
this.effect?.Dispose();
}
}
/// <summary>
/// A factory of a given shader instance.
/// </summary>
/// <param name="elapsedTime">The total elapsed time.</param>
/// <param name="screenWidth">The screen width in raw pixels.</param>
/// <param name="screenHeight">The screen height in raw pixels.</param>
/// <returns>A shader instance to render.</returns>
public delegate T Factory(TimeSpan elapsedTime, int screenWidth, int screenHeight);
}
}
+231
ファイルの表示
@@ -0,0 +1,231 @@
using System;
using System.Diagnostics.CodeAnalysis;
using ABI.Microsoft.Graphics.Canvas;
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;
using CanvasDevice = Microsoft.Graphics.Canvas.CanvasDevice;
using CanvasDrawingSession = Microsoft.Graphics.Canvas.CanvasDrawingSession;
using CanvasSwapChain = Microsoft.Graphics.Canvas.CanvasSwapChain;
using Windows = TerraFX.Interop.Windows.Windows;
/// <summary>
/// A simple Win32 application handling a D2D swapchain.
/// </summary>
internal sealed class Win32Application
{
/// <summary>
/// The <see cref="CanvasDevice"/> instance to use.
/// </summary>
private CanvasDevice? canvasDevice;
/// <summary>
/// The <see cref="CanvasSwapChain"/> instance to use to render frames.
/// </summary>
private CanvasSwapChain? canvasSwapChain;
/// <summary>
/// Whether or not the window has been resized and requires the buffers to be updated.
/// </summary>
private volatile bool isResizePending;
/// <summary>
/// The current screen width in raw pixels.
/// </summary>
private uint screenWidth;
/// <summary>
/// The current screen height in raw pixels.
/// </summary>
private uint screenHeight;
/// <summary>
/// Raised whenever a draw operation can be performed.
/// </summary>
public event EventHandler<DrawEventArgs>? Draw;
/// <summary>
/// Initializes the current application.
/// </summary>
/// <param name="hwnd">The handle for the window.</param>
[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<IUnknown> direct3DDeviceUnknown = default)
using (ComPtr<IDXGIFactory2> dxgiFactory2 = default)
using (ComPtr<IDXGISwapChain1> dxgiSwapChain1 = default)
{
HRESULT hresult;
// Extract the underlying Direct3D device from the canvas device.
// This is needed for CreateSwapChainForHwnd, as the owning device.
using (ComPtr<IUnknown> canvasDeviceUnknown = default)
using (ComPtr<IDirect3DDxgiInterfaceAccess> direct3DDxgiInterfaceAccess = default)
{
canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable<CanvasDevice>.FromManaged(canvasDevice));
hresult = canvasDeviceUnknown.CopyTo(direct3DDxgiInterfaceAccess.GetAddressOf());
ExceptionHelpers.ThrowExceptionForHR(hresult);
hresult = direct3DDxgiInterfaceAccess.Get()->GetInterface(Windows.__uuidof<IUnknown>(), (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<IDXGIFactory2>(), (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 = 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;
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<ICanvasFactoryNative> canvasFactoryNative = default;
// Get the activation factory for CanvasDevice
using (ComPtr<IUnknown> canvasFactoryNativeUnknown = default)
{
ICanvasFactoryNative.Interface canvasDeviceActivationFactory = CanvasDevice.As<ICanvasFactoryNative.Interface>();
canvasFactoryNativeUnknown.Attach((IUnknown*)MarshalInterface<ICanvasFactoryNative.Interface>.FromManaged(canvasDeviceActivationFactory));
hresult = canvasFactoryNativeUnknown.CopyTo(canvasFactoryNative.GetAddressOf());
ExceptionHelpers.ThrowExceptionForHR(hresult);
}
// Create a Win2D wrapper for the swapchain
using (ComPtr<IUnknown> canvasDeviceUnknown = default)
using (ComPtr<IUnknown> canvasSwapChainUnknown = default)
{
canvasDeviceUnknown.Attach((IUnknown*)MarshalInspectable<CanvasDevice>.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<CanvasSwapChain>.FromAbi((IntPtr)canvasSwapChainUnknown.Get());
}
}
// Save the Win2D objects for later use
this.canvasDevice = canvasDevice;
this.canvasSwapChain = canvasSwapChain;
}
/// <summary>
/// Resizes the current application.
/// </summary>
public void OnResize()
{
this.isResizePending = true;
}
/// <summary>
/// Updates the current application.
/// </summary>
/// <param name="time">The current time since the start of the application.</param>
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);
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
{
ScreenWidth = this.screenWidth,
ScreenHeight = this.screenHeight,
TotalTime = time,
DrawingSession = canvasDrawingSession
});
}
// Wait for v-sync
this.canvasSwapChain.WaitForVerticalBlank();
// Present the new frame
this.canvasSwapChain.Present(syncInterval: 1);
}
/// <summary>
/// Arguments for <see cref="Draw"/>.
/// </summary>
public sealed class DrawEventArgs : EventArgs
{
/// <summary>
/// Gets the screen width in raw pixels.
/// </summary>
public required uint ScreenWidth { get; init; }
/// <summary>
/// Gets the screen height in raw pixels.
/// </summary>
public required uint ScreenHeight { get; init; }
/// <summary>
/// Gets the total time for the rendering loop.
/// </summary>
public required TimeSpan TotalTime { get; init; }
/// <summary>
/// Gets the <see cref="CanvasDrawingSession"/> instance to use.
/// </summary>
public required CanvasDrawingSession DrawingSession { get; init; }
}
}
+344
ファイルの表示
@@ -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;
/// <summary>
/// A helper class to manage the creation and execution of Win32 applications.
/// </summary>
internal static unsafe class Win32ApplicationRunner
{
/// <summary>
/// Whether or not a resize operation is in progress.
/// </summary>
private static bool isResizing = false;
/// <summary>
/// Whether or not the application is currently paused.
/// </summary>
private static bool isPaused = false;
/// <summary>
/// The <see cref="HWND"/> for the application window.
/// </summary>
private static HWND hwnd;
/// <summary>
/// The application being run.
/// </summary>
private static Win32Application application = null!;
/// <summary>
/// The thread running the render loop.
/// </summary>
private static Thread renderThread = null!;
/// <summary>
/// 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.
/// </summary>
/// <param name="application">The input application instance to run.</param>
/// <param name="applicationName">Name of the input application instance to run.</param>
/// <param name="windowTitle">The title to use for the window being opened.</param>
/// <returns>The exit code for the application.</returns>
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;
}
/// <summary>
/// Processes incoming messages for a window.
/// </summary>
/// <param name="hwnd">A handle to the window.</param>
/// <param name="uMsg">The message.</param>
/// <param name="wParam">Additional message information (the contents depend on the value of <paramref name="uMsg"/>).</param>
/// <param name="lParam">Additional message information (the contents depend on the value of <paramref name="uMsg"/>).</param>
/// <returns>The result of the message processing for the input message.</returns>
[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);
}
}
+48
ファイルの表示
@@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType Condition="'$(CI_RUNNER_SAMPLES_INTEGRATION_TESTS)' == 'true'">Exe</OutputType>
<OutputType Condition="'$(CI_RUNNER_SAMPLES_INTEGRATION_TESTS)' != 'true'">WinExe</OutputType>
<TargetFramework>net7.0-windows10.0.22621</TargetFramework>
<ApplicationManifest>app.manifest</ApplicationManifest>
<Platforms>x64;ARM64</Platforms>
<NoWarn>$(NoWarn);IDE0065</NoWarn>
<AssemblyName>computesharp.d2d1.cli</AssemblyName>
<ApplicationIcon>..\ComputeSharp.SwapChain.Cli\icon.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<!-- Workaround for WinRT.TypeExtensions.GetAuthoringMetadataType(Type) trim warning (see https://github.com/microsoft/CsWinRT/issues/1319) -->
<NoWarn>$(NoWarn);IL2104;IL2026</NoWarn>
</PropertyGroup>
<!-- Same optional NativeAOT property group as in ComputeSharp.SwapChain.Cli -->
<PropertyGroup Condition="'$(COMPUTESHARP_SWAPCHAIN_D2D1_PUBLISH_AOT)' == 'true'">
<PublishAot>true</PublishAot>
<UseSystemResourceKeys>true</UseSystemResourceKeys>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Speed</IlcOptimizationPreference>
</PropertyGroup>
<!-- Also include the .rd.xml file to fix some NativeAOT issues with CsWinRT -->
<ItemGroup Condition="'$(COMPUTESHARP_SWAPCHAIN_D2D1_PUBLISH_AOT)' == 'true'">
<RdXmlFile Include="Properties\Default.rd.xml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="PolySharp" Version="1.13.1" PrivateAssets="all" />
<PackageReference Include="TerraFX.Interop.Windows" Version="10.0.22621.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.SourceGenerators\ComputeSharp.D2D1.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1.WinUI\ComputeSharp.D2D1.WinUI.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.D2D1\ComputeSharp.D2D1.csproj" />
</ItemGroup>
<Import Project="..\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems" Label="Shared" />
</Project>
+74
ファイルの表示
@@ -0,0 +1,74 @@
using System;
using ComputeSharp.SwapChain.D2D1.Backend;
using ComputeSharp.SwapChain.Shaders.D2D1;
using TerraFX.Interop.Windows;
// Accepted inputs:
// - []
// - [<SHADER_NAME>]
if (args is [] or [_])
{
// If there are no args, just run the default shader
if (args is not [string shaderName])
{
shaderName = nameof(ColorfulInfinity);
}
// Get the requested shader, if possible
PixelShaderEffect? effect = shaderName.ToLowerInvariant() switch
{
"helloworld" => new PixelShaderEffect.For<HelloWorld>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"colorfulinfinity" => new PixelShaderEffect.For<ColorfulInfinity>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"fractaltiling" => new PixelShaderEffect.For<FractalTiling>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"twotiledtruchet" => new PixelShaderEffect.For<TwoTiledTruchet>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"mengerjourney" => new PixelShaderEffect.For<MengerJourney>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"octagrams" => new PixelShaderEffect.For<Octagrams>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"proteanclouds" => new PixelShaderEffect.For<ProteanClouds>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"pyramidpattern" => new PixelShaderEffect.For<PyramidPattern>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"trianglegridcontouring" => new PixelShaderEffect.For<TriangleGridContouring>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
"terracedhills" => new PixelShaderEffect.For<TerracedHills>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height))),
_ => null
};
// If a shader is found, run it
if (effect is not null)
{
Win32Application win32Application = new();
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);
};
return Win32ApplicationRunner.Run(win32Application, "ComputeSharp.D2D1", "ComputeSharp.D2D1");
}
// 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;
+15
ファイルの表示
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<Directives>
<Application>
<Assembly Name="WinRT.Runtime">
<Type Name="WinRT.IObjectReference">
<Method Name="As" Dynamic="Required All">
<GenericArgument Name="ABI.Microsoft.Graphics.Canvas.ICanvasFactoryNative+Interface+Vftbl, ComputeSharp.SwapChain.D2D1" />
</Method>
<Method Name="As" Dynamic="Required All">
<GenericArgument Name="ABI.System.IDisposable+Vftbl, WinRT.Runtime" />
</Method>
</Type>
</Assembly>
</Application>
</Directives>
+9
ファイルの表示
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
</assembly>
+1 -1
ファイルの表示
@@ -71,7 +71,7 @@ internal sealed class SwapChainApplication<T> : Win32Application
/// <summary>
/// Whether or not the window has been resized and requires the buffers to be updated.
/// </summary>
private bool isResizePending;
private volatile bool isResizePending;
/// <summary>
/// Creates a new <see cref="SwapChainApplication{T}"/> instance with the specified parameters.
+1
ファイルの表示
@@ -340,6 +340,7 @@ internal static unsafe class Win32ApplicationRunner
case WM.WM_DESTROY:
{
Windows.PostQuitMessage(0);
return 0;
}
}