Refactor render code into 'CoreApplication' helpers

このコミットが含まれているのは:
Sergio Pedri committed 2024-09-26 18:14:50 -07:00
1 親 c011d531e0
コミット 35e21eadbd
5ファイル変更
+302 -37

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

+3 -3
ファイルの表示
@@ -33,9 +33,9 @@ if (args is [] or [_])
// If a shader is found, run it
if (effect is not null)
{
Win32Application win32Application = new();
Win32Application application = new();
win32Application.Draw += (_, e) =>
application.Draw += (_, e) =>
{
// Set the effect properties
effect.ElapsedTime = e.TotalTime;
@@ -46,7 +46,7 @@ if (args is [] or [_])
e.DrawingSession.DrawImage(effect);
};
Win32ApplicationRunner.Run(win32Application, "ComputeSharp.D2D1");
Win32ApplicationRunner.Run(application, "ComputeSharp.D2D1");
return S.S_OK;
}
+12 -34
ファイルの表示
@@ -1,14 +1,8 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using ComputeSharp.D2D1.Uwp;
using ComputeSharp.SwapChain.D2D1.Backend;
using ComputeSharp.SwapChain.D2D1.Extensions;
using ComputeSharp.SwapChain.Shaders.D2D1;
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Windows.ApplicationModel.Core;
using Windows.Graphics.Display;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
@@ -69,38 +63,22 @@ public sealed partial class App : IFrameworkViewSource, IFrameworkView
ApplicationView.GetForCurrentView().TitleBar.StyleTitleBarForExtendedIntoViewMode();
CanvasSwapChain swapChain = CanvasSwapChain.CreateForCoreWindow(
CanvasDevice.GetSharedDevice(),
this.window,
DisplayInformation.GetForCurrentView().LogicalDpi);
PixelShaderEffect effect = new PixelShaderEffect.For<ColorfulInfinity>(static (time, width, height) => new((float)time.TotalSeconds, new int2(width, height)));
int2 sizeInPixels = new((int)swapChain.SizeInPixels.Width, (int)swapChain.SizeInPixels.Height);
CancellationTokenSource cancellationTokenSource = new();
Stopwatch stopwatch = Stopwatch.StartNew();
CoreWindowApplication application = new();
Thread thread = new(() =>
application.Draw += (s, e) =>
{
PixelShaderEffect<ColorfulInfinity> shader = new();
PremultiplyEffect premultiply = new() { Source = shader };
// Set the effect properties
effect.ElapsedTime = e.TotalTime;
effect.ScreenWidth = (int)e.ScreenWidth;
effect.ScreenHeight = (int)e.ScreenHeight;
while (!cancellationTokenSource.IsCancellationRequested)
{
using (CanvasDrawingSession session = swapChain.CreateDrawingSession(Colors.Transparent))
{
shader.ConstantBuffer = new ColorfulInfinity((float)stopwatch.Elapsed.TotalSeconds, sizeInPixels);
// Draw the effect
e.DrawingSession.DrawImage(effect);
};
session.DrawImage(premultiply);
}
swapChain.Present(syncInterval: 1);
}
});
thread.Start();
this.window!.Activate();
this.window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit);
CoreWindowApplicationRunner.Run(application, this.window!);
}
/// <inheritdoc/>
+145
ファイルの表示
@@ -0,0 +1,145 @@
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Graphics.Canvas;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.UI.Core;
namespace ComputeSharp.SwapChain.D2D1.Backend;
/// <summary>
/// A simple <see cref="CoreWindow"/> application handling a D2D swapchain.
/// </summary>
internal sealed class CoreWindowApplication
{
/// <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="window">The <see cref="CoreWindow"/> instance.</param>
[MemberNotNull(nameof(canvasDevice))]
[MemberNotNull(nameof(canvasSwapChain))]
public unsafe void OnInitialize(CoreWindow window)
{
// Create a new canvas device, which will handle DX11/D2D initialization
CanvasDevice canvasDevice = new();
// Create the swapchain for rendering (it is automatically tied to the window)
CanvasSwapChain canvasSwapChain = CanvasSwapChain.CreateForCoreWindow(
resourceCreator: canvasDevice,
coreWindow: window,
dpi: DisplayInformation.GetForCurrentView().LogicalDpi);
// Save the Win2D objects for later use
this.canvasDevice = canvasDevice;
this.canvasSwapChain = canvasSwapChain;
// Store the initial size of the screen
this.screenWidth = canvasSwapChain.SizeInPixels.Width;
this.screenHeight = canvasSwapChain.SizeInPixels.Height;
}
/// <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: DisplayInformation.GetForCurrentView().LogicalDpi);
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; }
}
}
@@ -0,0 +1,53 @@
using System.Diagnostics;
using System.Threading;
using Windows.UI.Core;
namespace ComputeSharp.SwapChain.D2D1.Backend;
/// <summary>
/// A helper class to manage the creation and execution of <see cref="CoreWindow"/> applications.
/// </summary>
internal static class CoreWindowApplicationRunner
{
/// <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="window">The <see cref="CoreWindow"/> instance.</param>
public static void Run(CoreWindowApplication application, CoreWindow window)
{
// Initialize the application
application.OnInitialize(window);
// Setup the render thread that enables smooth resizing of the window
Thread renderThread = new(static args =>
{
(CoreWindowApplication application, CancellationToken token) = ((CoreWindowApplication, CancellationToken))args!;
Stopwatch stopwatch = Stopwatch.StartNew();
while (!token.IsCancellationRequested)
{
application.OnUpdate(stopwatch.Elapsed);
}
});
CancellationTokenSource tokenSource = new();
// Start the render thread before activating the window.
// This allows the app to show up while already drawing.
renderThread.Start((application, tokenSource.Token));
// Activate the window
window.Activate();
// Process any messages in the queue
window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit);
tokenSource.Cancel();
// Wait for the render thread to stop before terminating
renderThread.Join();
}
}
+89
ファイルの表示
@@ -0,0 +1,89 @@
using System;
using ComputeSharp.D2D1;
using ComputeSharp.D2D1.Descriptors;
using ComputeSharp.D2D1.Uwp;
namespace ComputeSharp.SwapChain.D2D1.Backend;
/// <summary>
/// An base effect for an animated pixel shader.
/// </summary>
internal abstract partial 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>
/// <param name="factory">The input <typeparamref name="T"/> factory.</param>
public sealed partial class For<T>(For<T>.Factory factory) : PixelShaderEffect
where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor<T>
{
/// <summary>
/// The <see cref="PixelShaderEffect{T}"/> node in use.
/// </summary>
private static readonly CanvasEffectNode<PixelShaderEffect<T>> Effect = new();
/// <inheritdoc/>
protected override void BuildEffectGraph(CanvasEffectGraph effectGraph)
{
effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect<T>());
}
/// <inheritdoc/>
protected override void ConfigureEffectGraph(CanvasEffectGraph effectGraph)
{
effectGraph.GetNode(Effect).ConstantBuffer = factory(ElapsedTime, ScreenWidth, ScreenHeight);
}
/// <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);
}
}