Move files from ComputeSharp.UI to WinUI project
このコミットが含まれているのは:
1 親
e188ef3ae0
コミット
58fbb2045a
14ファイル変更
-15
検索条件に一致するファイルはありません
@@ -8,19 +8,4 @@
|
||||
<PropertyGroup Label="Configuration">
|
||||
<Import_RootNamespace>ComputeSharp.UI</Import_RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Controls\AnimatedComputeShaderPanel.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Controls\AnimatedComputeShaderPanel.Properties.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Controls\ComputeShaderPanel.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Controls\ComputeShaderPanel.Properties.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Controls\RenderingFailedEventArgs.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IDXGIAdapterExtensions.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SemaphoreSlimExtensions.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SwapChainManager.Rendering.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Helpers\SwapChainManager.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Helpers\DynamicResolutionManager.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)IFrameRequestQueue.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)IShaderRunner.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ShaderRunner{T}.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,209 +0,0 @@
|
||||
using System;
|
||||
#if WINDOWS_UWP
|
||||
using Windows.UI.Xaml;
|
||||
#else
|
||||
using Microsoft.UI.Xaml;
|
||||
#endif
|
||||
using Windows.Foundation;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI;
|
||||
#endif
|
||||
|
||||
/// <inheritdoc cref="AnimatedComputeShaderPanel"/>
|
||||
partial class AnimatedComputeShaderPanel
|
||||
{
|
||||
/// <summary>
|
||||
/// Raised whenever rendering starts.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<AnimatedComputeShaderPanel, EventArgs>? RenderingStarted
|
||||
{
|
||||
add => this.swapChainManager.RenderingStarted += value;
|
||||
remove => this.swapChainManager.RenderingStarted -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever rendering stops.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<AnimatedComputeShaderPanel, EventArgs>? RenderingStopped
|
||||
{
|
||||
add => this.swapChainManager.RenderingStopped += value;
|
||||
remove => this.swapChainManager.RenderingStopped -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever rendering fails.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<AnimatedComputeShaderPanel, RenderingFailedEventArgs>? RenderingFailed
|
||||
{
|
||||
add => this.swapChainManager.RenderingFailed += value;
|
||||
remove => this.swapChainManager.RenderingFailed -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever the <see cref="AnimatedComputeShaderPanel"/> control is disposed and all underlying resources are released.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<AnimatedComputeShaderPanel, EventArgs>? Disposed
|
||||
{
|
||||
add => this.swapChainManager.Disposed += value;
|
||||
remove => this.swapChainManager.Disposed -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="IShaderRunner"/> instance to use to render content.
|
||||
/// </summary>
|
||||
public IShaderRunner? ShaderRunner
|
||||
{
|
||||
get => (IShaderRunner?)GetValue(ShaderRunnerProperty);
|
||||
set => SetValue(ShaderRunnerProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="ShaderRunner"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty ShaderRunnerProperty = DependencyProperty.Register(
|
||||
nameof(ShaderRunner),
|
||||
typeof(IShaderRunner),
|
||||
typeof(AnimatedComputeShaderPanel),
|
||||
new PropertyMetadata(null, OnShaderRunnerPropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnShaderRunnerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
AnimatedComputeShaderPanel @this = (AnimatedComputeShaderPanel)d;
|
||||
|
||||
if (@this.IsLoaded &&
|
||||
!@this.IsPaused &&
|
||||
e.NewValue is IShaderRunner shaderRunner)
|
||||
{
|
||||
@this.swapChainManager.StartRenderLoop(null, shaderRunner);
|
||||
}
|
||||
else
|
||||
{
|
||||
@this.swapChainManager.StopRenderLoop();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resolution scale to be used to render frames.
|
||||
/// This can help achieve higher framerates with more complex shaders.
|
||||
/// </summary>
|
||||
/// <remarks>The accepted range is [0.1 and 1] (default is 1, exceeding values will be clamped).</remarks>
|
||||
public double ResolutionScale
|
||||
{
|
||||
get => (double)GetValue(ResolutionScaleProperty);
|
||||
set => SetValue(ResolutionScaleProperty, Math.Clamp(value, 0.1, 1.0));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="ResolutionScale"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty ResolutionScaleProperty = DependencyProperty.Register(
|
||||
nameof(ResolutionScale),
|
||||
typeof(double),
|
||||
typeof(AnimatedComputeShaderPanel),
|
||||
new PropertyMetadata(1.0, OnResolutionScalePropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnResolutionScalePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
AnimatedComputeShaderPanel @this = (AnimatedComputeShaderPanel)d;
|
||||
double resolutionScale = (double)e.NewValue;
|
||||
|
||||
@this.swapChainManager.QueueResolutionScaleChange(resolutionScale);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether dynamic resolution is enabled. If it is, the internal render
|
||||
/// resolution of the shader being run will be automatically adjusted to reach 60fps.
|
||||
/// <para>The default value for this property is <see langword="true"/>.</para>
|
||||
/// </summary>
|
||||
public bool IsDynamicResolutionEnabled
|
||||
{
|
||||
get => (bool)GetValue(IsDynamicResolutionEnabledProperty);
|
||||
set => SetValue(IsDynamicResolutionEnabledProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="IsDynamicResolutionEnabled"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty IsDynamicResolutionEnabledProperty = DependencyProperty.Register(
|
||||
nameof(IsDynamicResolutionEnabled),
|
||||
typeof(bool),
|
||||
typeof(AnimatedComputeShaderPanel),
|
||||
new PropertyMetadata(true, OnIsDynamicResolutionEnabledPropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnIsDynamicResolutionEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
AnimatedComputeShaderPanel @this = (AnimatedComputeShaderPanel)d;
|
||||
bool isDynamicResolutionEnabled = (bool)e.NewValue;
|
||||
|
||||
@this.swapChainManager.QueueDynamicResolutionModeChange(isDynamicResolutionEnabled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether vertical sync is enabled.
|
||||
/// <para>The default value for this property is <see langword="true"/>.</para>
|
||||
/// </summary>
|
||||
public bool IsVerticalSyncEnabled
|
||||
{
|
||||
get => (bool)GetValue(IsVerticalSyncEnabledProperty);
|
||||
set => SetValue(IsVerticalSyncEnabledProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="IsVerticalSyncEnabled"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty IsVerticalSyncEnabledProperty = DependencyProperty.Register(
|
||||
nameof(IsVerticalSyncEnabled),
|
||||
typeof(bool),
|
||||
typeof(AnimatedComputeShaderPanel),
|
||||
new PropertyMetadata(true, OnIsVerticalSyncEnabledPropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnIsVerticalSyncEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
AnimatedComputeShaderPanel @this = (AnimatedComputeShaderPanel)d;
|
||||
bool isVerticalSyncEnabled = (bool)e.NewValue;
|
||||
|
||||
@this.swapChainManager.QueueVerticalSyncModeChange(isVerticalSyncEnabled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether or not the rendering is paused.
|
||||
/// </summary>
|
||||
public bool IsPaused
|
||||
{
|
||||
get => (bool)GetValue(IsPausedProperty);
|
||||
set => SetValue(IsPausedProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="IsPaused"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty IsPausedProperty = DependencyProperty.Register(
|
||||
nameof(IsPaused),
|
||||
typeof(bool),
|
||||
typeof(AnimatedComputeShaderPanel),
|
||||
new PropertyMetadata(false, OnIsPausedPropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnIsPausedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
AnimatedComputeShaderPanel @this = (AnimatedComputeShaderPanel)d;
|
||||
|
||||
if (@this.IsLoaded &&
|
||||
(bool)e.NewValue is false &&
|
||||
@this.ShaderRunner is IShaderRunner shaderRunner)
|
||||
{
|
||||
@this.swapChainManager.StartRenderLoop(null, shaderRunner);
|
||||
}
|
||||
else
|
||||
{
|
||||
@this.swapChainManager.StopRenderLoop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
using System;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.Uwp.Helpers;
|
||||
using Windows.UI.Xaml;
|
||||
using Windows.UI.Xaml.Controls;
|
||||
#else
|
||||
using ComputeSharp.WinUI.Helpers;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// <para>
|
||||
/// A custom <see cref="SwapChainPanel"/> that can be used to render animated backgrounds.
|
||||
/// It is powered by ComputeSharp and leverages compute shaders to create frames to display.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This panel will always render new frames at the current display refresh rate, automatically.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="SwapChainManager{TOwner}"/> instance handling rendering.
|
||||
/// </summary>
|
||||
private readonly SwapChainManager<AnimatedComputeShaderPanel> swapChainManager;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="AnimatedComputeShaderPanel"/> instance.
|
||||
/// </summary>
|
||||
public AnimatedComputeShaderPanel()
|
||||
: this(GraphicsDevice.GetDefault())
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="AnimatedComputeShaderPanel"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to render frames.</param>
|
||||
public AnimatedComputeShaderPanel(GraphicsDevice device)
|
||||
{
|
||||
this.swapChainManager = new SwapChainManager<AnimatedComputeShaderPanel>(this, device);
|
||||
|
||||
Loaded += AnimatedComputeShaderPanel_Loaded;
|
||||
Unloaded += AnimatedComputeShaderPanel_Unloaded;
|
||||
SizeChanged += AnimatedComputeShaderPanel_SizeChanged;
|
||||
CompositionScaleChanged += AnimatedComputeShaderPanel_CompositionScaleChanged;
|
||||
}
|
||||
|
||||
// Initializes the swap chain and starts the render thread
|
||||
private void AnimatedComputeShaderPanel_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
this.swapChainManager.QueueResize(ActualWidth, ActualHeight);
|
||||
this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY);
|
||||
this.swapChainManager.QueueResolutionScaleChange(ResolutionScale);
|
||||
this.swapChainManager.QueueDynamicResolutionModeChange(IsDynamicResolutionEnabled);
|
||||
this.swapChainManager.QueueVerticalSyncModeChange(IsVerticalSyncEnabled);
|
||||
|
||||
if (!IsPaused &&
|
||||
ShaderRunner is IShaderRunner shaderRunner)
|
||||
{
|
||||
this.swapChainManager.StartRenderLoop(null, shaderRunner);
|
||||
}
|
||||
}
|
||||
|
||||
// Requests a cancellation for the render thread
|
||||
private void AnimatedComputeShaderPanel_Unloaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
this.swapChainManager.StopRenderLoop();
|
||||
}
|
||||
|
||||
// Updates the background store for the frame size factors used by the render thread
|
||||
private void AnimatedComputeShaderPanel_SizeChanged(object sender, SizeChangedEventArgs e)
|
||||
{
|
||||
this.swapChainManager.QueueResize(e.NewSize.Width, e.NewSize.Height);
|
||||
}
|
||||
|
||||
// Updates the background store for the composition scale factors used by the render thread
|
||||
private void AnimatedComputeShaderPanel_CompositionScaleChanged(SwapChainPanel sender, object args)
|
||||
{
|
||||
this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
// Also request the render loop to stop before disposing. This ensures that in case there's
|
||||
// a render thread already ongoing that is using a custom frame request queue, it might have
|
||||
// the ability to stop rendering immediately and safely, instead of causing the panel to remain
|
||||
// alive and then just throwing an exception the next time a frame is requested in case the
|
||||
// device ot other resources have also been disposed.
|
||||
this.swapChainManager.StopRenderLoop();
|
||||
this.swapChainManager.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
using System;
|
||||
#if WINDOWS_UWP
|
||||
using Windows.UI.Xaml;
|
||||
#else
|
||||
using Microsoft.UI.Xaml;
|
||||
#endif
|
||||
using Windows.Foundation;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI;
|
||||
#endif
|
||||
|
||||
/// <inheritdoc cref="ComputeShaderPanel"/>
|
||||
partial class ComputeShaderPanel
|
||||
{
|
||||
/// <summary>
|
||||
/// Raised whenever rendering starts.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<ComputeShaderPanel, EventArgs>? RenderingStarted
|
||||
{
|
||||
add => this.swapChainManager.RenderingStarted += value;
|
||||
remove => this.swapChainManager.RenderingStarted -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever rendering stops.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<ComputeShaderPanel, EventArgs>? RenderingStopped
|
||||
{
|
||||
add => this.swapChainManager.RenderingStopped += value;
|
||||
remove => this.swapChainManager.RenderingStopped -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever rendering fails.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<ComputeShaderPanel, RenderingFailedEventArgs>? RenderingFailed
|
||||
{
|
||||
add => this.swapChainManager.RenderingFailed += value;
|
||||
remove => this.swapChainManager.RenderingFailed -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever the <see cref="ComputeShaderPanel"/> control is disposed and all underlying resources are released.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<ComputeShaderPanel, EventArgs>? Disposed
|
||||
{
|
||||
add => this.swapChainManager.Disposed += value;
|
||||
remove => this.swapChainManager.Disposed -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="IFrameRequestQueue"/> instance to use to request new frames.
|
||||
/// </summary>
|
||||
public IFrameRequestQueue? FrameRequestQueue
|
||||
{
|
||||
get => (IFrameRequestQueue)GetValue(FrameRequestQueueProperty);
|
||||
set => SetValue(FrameRequestQueueProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="ShaderRunner"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty FrameRequestQueueProperty = DependencyProperty.Register(
|
||||
nameof(FrameRequestQueue),
|
||||
typeof(IFrameRequestQueue),
|
||||
typeof(ComputeShaderPanel),
|
||||
new PropertyMetadata(null, OnFrameRequestQueueChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnFrameRequestQueueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
ComputeShaderPanel @this = (ComputeShaderPanel)d;
|
||||
|
||||
if (@this.IsLoaded &&
|
||||
e.NewValue is IFrameRequestQueue frameRequestQueue &&
|
||||
@this.ShaderRunner is IShaderRunner shaderRunner)
|
||||
{
|
||||
@this.swapChainManager.StartRenderLoop(frameRequestQueue, shaderRunner);
|
||||
}
|
||||
else
|
||||
{
|
||||
@this.swapChainManager.StopRenderLoop();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="IShaderRunner"/> instance to use to render content.
|
||||
/// </summary>
|
||||
public IShaderRunner? ShaderRunner
|
||||
{
|
||||
get => (IShaderRunner?)GetValue(ShaderRunnerProperty);
|
||||
set => SetValue(ShaderRunnerProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="ShaderRunner"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty ShaderRunnerProperty = DependencyProperty.Register(
|
||||
nameof(ShaderRunner),
|
||||
typeof(IShaderRunner),
|
||||
typeof(ComputeShaderPanel),
|
||||
new PropertyMetadata(null, OnShaderRunnerPropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnShaderRunnerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
ComputeShaderPanel @this = (ComputeShaderPanel)d;
|
||||
|
||||
if (@this.IsLoaded &&
|
||||
@this.FrameRequestQueue is IFrameRequestQueue frameRequestQueue &&
|
||||
e.NewValue is IShaderRunner shaderRunner)
|
||||
{
|
||||
@this.swapChainManager.StartRenderLoop(frameRequestQueue, shaderRunner);
|
||||
}
|
||||
else
|
||||
{
|
||||
@this.swapChainManager.StopRenderLoop();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the resolution scale to be used to render frames.
|
||||
/// This can help achieve higher framerates with more complex shaders.
|
||||
/// </summary>
|
||||
/// <remarks>The accepted range is [0.1 and 1] (default is 1, exceeding values will be clamped).</remarks>
|
||||
public double ResolutionScale
|
||||
{
|
||||
get => (double)GetValue(ResolutionScaleProperty);
|
||||
set => SetValue(ResolutionScaleProperty, Math.Clamp(value, 0.1, 1.0));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="ResolutionScale"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty ResolutionScaleProperty = DependencyProperty.Register(
|
||||
nameof(ResolutionScale),
|
||||
typeof(double),
|
||||
typeof(ComputeShaderPanel),
|
||||
new PropertyMetadata(1.0, OnResolutionScalePropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnResolutionScalePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
ComputeShaderPanel @this = (ComputeShaderPanel)d;
|
||||
double resolutionScale = (double)e.NewValue;
|
||||
|
||||
@this.swapChainManager.QueueResolutionScaleChange(resolutionScale);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether dynamic resolution is enabled. If it is, the internal render
|
||||
/// resolution of the shader being run will be automatically adjusted to reach 60fps.
|
||||
/// <para>The default value for this property is <see langword="true"/>.</para>
|
||||
/// </summary>
|
||||
public bool IsDynamicResolutionEnabled
|
||||
{
|
||||
get => (bool)GetValue(IsDynamicResolutionEnabledProperty);
|
||||
set => SetValue(IsDynamicResolutionEnabledProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="IsDynamicResolutionEnabled"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty IsDynamicResolutionEnabledProperty = DependencyProperty.Register(
|
||||
nameof(IsDynamicResolutionEnabled),
|
||||
typeof(bool),
|
||||
typeof(ComputeShaderPanel),
|
||||
new PropertyMetadata(true, OnIsDynamicResolutionEnabledPropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnIsDynamicResolutionEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
ComputeShaderPanel @this = (ComputeShaderPanel)d;
|
||||
bool isDynamicResolutionEnabled = (bool)e.NewValue;
|
||||
|
||||
@this.swapChainManager.QueueDynamicResolutionModeChange(isDynamicResolutionEnabled);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether vertical sync is enabled.
|
||||
/// <para>The default value for this property is <see langword="true"/>.</para>
|
||||
/// </summary>
|
||||
public bool IsVerticalSyncEnabled
|
||||
{
|
||||
get => (bool)GetValue(IsVerticalSyncEnabledProperty);
|
||||
set => SetValue(IsVerticalSyncEnabledProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="DependencyProperty"/> backing <see cref="IsVerticalSyncEnabled"/>.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty IsVerticalSyncEnabledProperty = DependencyProperty.Register(
|
||||
nameof(IsVerticalSyncEnabled),
|
||||
typeof(bool),
|
||||
typeof(ComputeShaderPanel),
|
||||
new PropertyMetadata(true, OnIsVerticalSyncEnabledPropertyChanged));
|
||||
|
||||
/// <inheritdoc cref="DependencyPropertyChangedCallback"/>
|
||||
private static void OnIsVerticalSyncEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
ComputeShaderPanel @this = (ComputeShaderPanel)d;
|
||||
bool isVerticalSyncEnabled = (bool)e.NewValue;
|
||||
|
||||
@this.swapChainManager.QueueVerticalSyncModeChange(isVerticalSyncEnabled);
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
using System;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.Uwp.Helpers;
|
||||
using Windows.UI.Xaml;
|
||||
using Windows.UI.Xaml.Controls;
|
||||
#else
|
||||
using ComputeSharp.WinUI.Helpers;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// <para>
|
||||
/// A custom <see cref="SwapChainPanel"/> that can be used to render animated backgrounds.
|
||||
/// It is powered by ComputeSharp and leverages compute shaders to create frames to display.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This panel accepts a custom <see cref="IFrameRequestQueue"/> instance to customize frame requests.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed partial class ComputeShaderPanel : SwapChainPanel, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="SwapChainManager{TOwner}"/> instance handling rendering.
|
||||
/// </summary>
|
||||
private readonly SwapChainManager<ComputeShaderPanel> swapChainManager;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ComputeShaderPanel"/> instance.
|
||||
/// </summary>
|
||||
public ComputeShaderPanel()
|
||||
: this(GraphicsDevice.GetDefault())
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ComputeShaderPanel"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to render frames.</param>
|
||||
public ComputeShaderPanel(GraphicsDevice device)
|
||||
{
|
||||
this.swapChainManager = new SwapChainManager<ComputeShaderPanel>(this, device);
|
||||
|
||||
Loaded += ComputeShaderPanel_Loaded;
|
||||
Unloaded += ComputeShaderPanel_Unloaded;
|
||||
SizeChanged += ComputeShaderPanel_SizeChanged;
|
||||
CompositionScaleChanged += ComputeShaderPanel_CompositionScaleChanged;
|
||||
}
|
||||
|
||||
// Initializes the swap chain and starts the render thread
|
||||
private void ComputeShaderPanel_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
this.swapChainManager.QueueResize(ActualWidth, ActualHeight);
|
||||
this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY);
|
||||
this.swapChainManager.QueueResolutionScaleChange(ResolutionScale);
|
||||
this.swapChainManager.QueueDynamicResolutionModeChange(IsDynamicResolutionEnabled);
|
||||
this.swapChainManager.QueueVerticalSyncModeChange(IsVerticalSyncEnabled);
|
||||
|
||||
if (FrameRequestQueue is IFrameRequestQueue frameRequestQueue &&
|
||||
ShaderRunner is IShaderRunner shaderRunner)
|
||||
{
|
||||
this.swapChainManager.StartRenderLoop(frameRequestQueue, shaderRunner);
|
||||
}
|
||||
}
|
||||
|
||||
// Requests a cancellation for the render thread
|
||||
private void ComputeShaderPanel_Unloaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
this.swapChainManager.StopRenderLoop();
|
||||
}
|
||||
|
||||
// Updates the background store for the frame size factors used by the render thread
|
||||
private void ComputeShaderPanel_SizeChanged(object sender, SizeChangedEventArgs e)
|
||||
{
|
||||
this.swapChainManager.QueueResize(e.NewSize.Width, e.NewSize.Height);
|
||||
}
|
||||
|
||||
// Updates the background store for the composition scale factors used by the render thread
|
||||
private void ComputeShaderPanel_CompositionScaleChanged(SwapChainPanel sender, object args)
|
||||
{
|
||||
this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
this.swapChainManager.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
using System;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// The arguments for the <see cref="AnimatedComputeShaderPanel.RenderingFailed"/> and <see cref="ComputeShaderPanel.RenderingFailed"/> events.
|
||||
/// </summary>
|
||||
public sealed class RenderingFailedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="RenderingFailedEventArgs"/> instance with the specified arguments.
|
||||
/// </summary>
|
||||
/// <param name="exception">The <see cref="System.Exception"/> that caused the rendering to fail.</param>
|
||||
internal RenderingFailedEventArgs(Exception exception)
|
||||
{
|
||||
Exception = exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="System.Exception"/> that caused the rendering to fail.
|
||||
/// </summary>
|
||||
public Exception Exception { get; }
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
using System;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
using ComputeSharp.Graphics.Helpers;
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
using Win32 = TerraFX.Interop.Windows.Windows;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp.Extensions;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI.Extensions;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> with extensions for the <see cref="IDXGIAdapter"/> type.
|
||||
/// </summary>
|
||||
internal static unsafe class IDXGIAdapterExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Calculates the refresh rate for a given adapter.
|
||||
/// </summary>
|
||||
/// <param name="dxgiAdapter">The input adapter to query.</param>
|
||||
/// <param name="dxgiFormat">The <see cref="DXGI_FORMAT"/> in use to render content.</param>
|
||||
/// <returns>The current composition refresh rate.</returns>
|
||||
public static int GetCompositionRefreshRate(this ref IDXGIAdapter dxgiAdapter, DXGI_FORMAT dxgiFormat)
|
||||
{
|
||||
using ComPtr<IDXGIAdapter1> dxgiAdapter1 = default;
|
||||
|
||||
dxgiAdapter.QueryInterface(Win32.__uuidof<IDXGIAdapter1>(), dxgiAdapter1.GetVoidAddressOf()).Assert();
|
||||
|
||||
using ComPtr<IDXGIOutput> dxgiOutput = default;
|
||||
|
||||
// Get the first output for the adapter (this will match the compositor output)
|
||||
HRESULT hresult = dxgiAdapter1.Get()->EnumOutputs(0, dxgiOutput.GetAddressOf());
|
||||
|
||||
// There is a corner case to handle in case the WARP device is used (which will happen if running on a device
|
||||
// that doesn't have a dedicated GPU matching the minimum requirements for ComputeSharp, or if no dedicated
|
||||
// GPU is available at all). For WARP devices, there will never be any outputs being reported, so the call
|
||||
// above will fail with DXGI_ERROR_NOT_FOUND. In this case, instead of throwing, we can simply default to
|
||||
// a standard framerate of 60fps, and use that to still allow the execution to continue without crashing.
|
||||
if (hresult == DXGI.DXGI_ERROR_NOT_FOUND)
|
||||
{
|
||||
DXGI_ADAPTER_DESC dxgiDescription;
|
||||
|
||||
// Get the adapter description, to verify the device is in fact the WARP device
|
||||
dxgiAdapter.GetDesc(&dxgiDescription).Assert();
|
||||
|
||||
// Just default to 60fps if the WARP device is used
|
||||
if (dxgiDescription.VendorId == DeviceHelper.MicrosoftVendorId &&
|
||||
dxgiDescription.DeviceId == DeviceHelper.WarpDeviceId)
|
||||
{
|
||||
return 60;
|
||||
}
|
||||
}
|
||||
|
||||
hresult.Assert();
|
||||
|
||||
using ComPtr<IDXGIOutput1> dxgiOutput1 = default;
|
||||
|
||||
dxgiOutput.CopyTo(dxgiOutput1.GetAddressOf()).Assert();
|
||||
|
||||
DXGI_MODE_DESC1 dxgiModeDescIn = default;
|
||||
|
||||
dxgiModeDescIn.Format = dxgiFormat;
|
||||
|
||||
DXGI_MODE_DESC1 dxgiModeDescOut = default;
|
||||
|
||||
dxgiOutput1.Get()->FindClosestMatchingMode1(&dxgiModeDescIn, &dxgiModeDescOut, null).Assert();
|
||||
|
||||
// Calculates the best target framerate based on monitor refresh rate. Even with v-sync disabled, the target framerate
|
||||
// should always match the refresh rate in use, instead of being capped to 60fps (as users could have a 120Hz screen
|
||||
// and disabled v-sync). Here the refresh rate is retrieved, then the target framerate is calculated as being the
|
||||
// rounding up of this value to the next integer, and then clamped between 30 and 360fps.
|
||||
double refreshRateInHz = dxgiModeDescOut.RefreshRate.Numerator / (double)dxgiModeDescOut.RefreshRate.Denominator;
|
||||
int refreshRate = Math.Clamp((int)Math.Ceiling(refreshRateInHz), 30, 360);
|
||||
|
||||
return refreshRate;
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp.Extensions;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI.Extensions;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A helper type for <see cref="SemaphoreSlim"/>.
|
||||
/// </summary>
|
||||
internal static class SemaphoreSlimExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Acquires a lock for the current instance, that is automatically released outside the <see langword="using"/> block.
|
||||
/// </summary>
|
||||
public static async ValueTask<Lock> LockAsync(this SemaphoreSlim semaphore)
|
||||
{
|
||||
await semaphore.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
return new(semaphore);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private class that implements the automatic release of the semaphore
|
||||
/// </summary>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public readonly struct Lock : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The underlying semaphore used by this instance.
|
||||
/// </summary>
|
||||
private readonly SemaphoreSlim semaphore;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Lock"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="semaphore">The <see cref="SemaphoreSlim"/> instance to wrap.</param>
|
||||
[Obsolete("Use AsyncMutex.LockAsync instead.")]
|
||||
public Lock(SemaphoreSlim semaphore)
|
||||
{
|
||||
this.semaphore = semaphore;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
_ = this.semaphore.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp.Helpers;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI.Helpers;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A helper type that is responsible for applying dynamic resolution changes.
|
||||
/// </summary>
|
||||
internal unsafe ref struct DynamicResolutionManager
|
||||
{
|
||||
/// <summary>
|
||||
/// The size of the sliding frame time window to monitor frame times.
|
||||
/// </summary>
|
||||
private const int SlidingFrameTimeWindowLength = 32;
|
||||
|
||||
/// <summary>
|
||||
/// The threshold for scale factor updates.
|
||||
/// </summary>
|
||||
private const float ScaleFactorDeltaThreshold = 0.005f;
|
||||
|
||||
/// <summary>
|
||||
/// The constant multiplicative factor for the scale factor.
|
||||
/// </summary>
|
||||
private const float ScaleFactorDeltaK = 0.8f;
|
||||
|
||||
/// <summary>
|
||||
/// The target frame time in ticks.
|
||||
/// </summary>
|
||||
private readonly long targetFrameTimeInTicks;
|
||||
|
||||
/// <summary>
|
||||
/// The upper frame time threshold in ticks.
|
||||
/// </summary>
|
||||
private readonly long upperFrameTimeThresholdInTicks;
|
||||
|
||||
/// <summary>
|
||||
/// The lower frame time threshold in ticks.
|
||||
/// </summary>
|
||||
private readonly long lowerFrameTimeThresholdInTicks;
|
||||
|
||||
/// <summary>
|
||||
/// The window of registered frame times for previous frames.
|
||||
/// </summary>
|
||||
private fixed long frameTimesInTicks[SlidingFrameTimeWindowLength];
|
||||
|
||||
/// <summary>
|
||||
/// The current index into <see cref="frameTimesInTicks"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This will have a value of <c>-1</c> when a scale factor update has just been applied, indicating
|
||||
/// that the following frame update should not be tracked to contribute towards the next dynamic resolution
|
||||
/// check. This is done to avoid having the swap chain resize cost influence the moving average of frame times.
|
||||
/// </remarks>
|
||||
private int frameTimeOffset;
|
||||
|
||||
/// <summary>
|
||||
/// The current sum of values within <see cref="frameTimesInTicks"/>.
|
||||
/// </summary>
|
||||
private long slidingFrameTimeWindowSum;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new <see cref="DynamicResolutionManager"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="targetFramerate">The target framerate to use.</param>
|
||||
public DynamicResolutionManager(int targetFramerate)
|
||||
{
|
||||
long targetFrameTimeInTicks = TimeSpan.FromSeconds(1).Ticks / targetFramerate;
|
||||
long upperFrameTimeThresholdInTicks = TimeSpan.FromSeconds(1).Ticks / (targetFramerate - 2);
|
||||
long lowerFrameTimeThresholdInTicks = TimeSpan.FromSeconds(1).Ticks / (targetFramerate + 2);
|
||||
|
||||
this.frameTimeOffset = 0;
|
||||
this.targetFrameTimeInTicks = targetFrameTimeInTicks;
|
||||
this.upperFrameTimeThresholdInTicks = upperFrameTimeThresholdInTicks;
|
||||
this.lowerFrameTimeThresholdInTicks = lowerFrameTimeThresholdInTicks;
|
||||
this.slidingFrameTimeWindowSum = targetFrameTimeInTicks * SlidingFrameTimeWindowLength;
|
||||
|
||||
new Span<long>(Unsafe.AsPointer(ref this.frameTimesInTicks[0]), SlidingFrameTimeWindowLength).Fill(targetFrameTimeInTicks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Advances one frame and updates the scale factor, if needed.
|
||||
/// </summary>
|
||||
/// <param name="frameTimeInTicks">The frame time in ticks for the last rendered frame.</param>
|
||||
/// <param name="scaleFactor">The current scale factor value being used to render frames.</param>
|
||||
/// <returns>Whether or not <paramref name="scaleFactor"/> has been updated and a resize is needed.</returns>
|
||||
public bool Advance(long frameTimeInTicks, ref float scaleFactor)
|
||||
{
|
||||
// Ignore the current frame if a resize has just happened
|
||||
if (this.frameTimeOffset == -1)
|
||||
{
|
||||
this.frameTimeOffset = 0;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
ref long previousFrameTimeInTicks = ref this.frameTimesInTicks[this.frameTimeOffset];
|
||||
|
||||
this.slidingFrameTimeWindowSum -= previousFrameTimeInTicks;
|
||||
this.slidingFrameTimeWindowSum += frameTimeInTicks;
|
||||
|
||||
previousFrameTimeInTicks = frameTimeInTicks;
|
||||
|
||||
this.frameTimeOffset = (int)(((uint)this.frameTimeOffset + 1) % SlidingFrameTimeWindowLength);
|
||||
|
||||
// Check for a dynamic resolution update if the end of the sliding window has been reached.
|
||||
// This is not done every frame to reduce the overhead and amortize for render time fluctuations.
|
||||
if (this.frameTimeOffset == 0)
|
||||
{
|
||||
// This formula is adapted from https://software.intel.com/content/www/us/en/develop/articles/dynamic-resolution-rendering-article.html.
|
||||
long averageFrameTimeInTicks = this.slidingFrameTimeWindowSum / SlidingFrameTimeWindowLength;
|
||||
|
||||
if (averageFrameTimeInTicks < this.lowerFrameTimeThresholdInTicks ||
|
||||
averageFrameTimeInTicks > this.upperFrameTimeThresholdInTicks)
|
||||
{
|
||||
float frameTimeDelta = (this.targetFrameTimeInTicks - averageFrameTimeInTicks) / (float)averageFrameTimeInTicks;
|
||||
float scaleFactorDelta = scaleFactor * frameTimeDelta * ScaleFactorDeltaK;
|
||||
float updatedScaleFactor = Math.Clamp(scaleFactor + scaleFactorDelta, 0.10f, 1.0f);
|
||||
|
||||
// Apply the scale factor update if the target scale has changed enough. This helps to avoid
|
||||
// too frequence resolution changes if the scale factor only changes very little every time.
|
||||
if (Math.Abs(scaleFactor - updatedScaleFactor) >= ScaleFactorDeltaThreshold)
|
||||
{
|
||||
Volatile.Write(ref scaleFactor, updatedScaleFactor);
|
||||
|
||||
this.frameTimeOffset = -1;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using ComputeSharp.Interop;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.Uwp.Extensions;
|
||||
#else
|
||||
using ComputeSharp.WinUI.Extensions;
|
||||
#endif
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp.Helpers;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI.Helpers;
|
||||
#endif
|
||||
|
||||
#pragma warning disable CS0420
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class SwapChainManager<TOwner>
|
||||
{
|
||||
/// <summary>
|
||||
/// Starts the current render loop.
|
||||
/// </summary>
|
||||
/// <param name="frameRequestQueue">The <see cref="IFrameRequestQueue"/> instance to use, if available.</param>
|
||||
/// <param name="shaderRunner">The <see cref="IShaderRunner"/> instance to use to render frames.</param>
|
||||
public async void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner)
|
||||
{
|
||||
default(ArgumentNullException).ThrowIfNull(shaderRunner);
|
||||
|
||||
using (await this.setupSemaphore.LockAsync())
|
||||
{
|
||||
// Here and in the calls below, only get a reference tracking lease when starting a render thread.
|
||||
// This avoids crashes when the panel has been disposed but some code (eg. event handlers) still
|
||||
// ends up calling into any of the APIs in this file, which is not intended but should not crash.
|
||||
using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease();
|
||||
|
||||
this.renderCancellationTokenSource?.Cancel();
|
||||
|
||||
await this.renderSemaphore.WaitAsync();
|
||||
|
||||
Thread newRenderThread = new(static args => ((SwapChainManager<TOwner>)args!).SwitchAndStartRenderLoop());
|
||||
|
||||
this.frameRequestQueue = frameRequestQueue;
|
||||
this.shaderRunner = shaderRunner;
|
||||
this.renderCancellationTokenSource = new CancellationTokenSource();
|
||||
this.renderThread = newRenderThread;
|
||||
this.renderSemaphore = new SemaphoreSlim(0, 1);
|
||||
this.isResizePending = true;
|
||||
|
||||
newRenderThread.Start(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the current render loop, if one is running.
|
||||
/// </summary>
|
||||
public async void StopRenderLoop()
|
||||
{
|
||||
// Stopping the render loop doesn't use a reference tracking lease on purpose.
|
||||
// This is to allow callers to stop the render loop even after disposing without
|
||||
// the method throwing an exception. Stopping a loop doesn't actually access any
|
||||
// native objects anyway, as it's just cancelling the cancellation token source.
|
||||
using (await this.setupSemaphore.LockAsync())
|
||||
{
|
||||
this.renderCancellationTokenSource?.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues a change in the dynamic resolution mode.
|
||||
/// </summary>
|
||||
/// <param name="isDynamicResolutionEnabled">Whether or not to use dynamic resolution.</param>
|
||||
public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled)
|
||||
{
|
||||
using (await this.setupSemaphore.LockAsync())
|
||||
{
|
||||
// If there is a render thread currently running, stop it and restart it
|
||||
if (this.renderCancellationTokenSource?.IsCancellationRequested == false)
|
||||
{
|
||||
using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease();
|
||||
|
||||
this.renderCancellationTokenSource?.Cancel();
|
||||
|
||||
await this.renderSemaphore.WaitAsync();
|
||||
|
||||
Thread newRenderThread = new(static args => ((SwapChainManager<TOwner>)args!).SwitchAndStartRenderLoop());
|
||||
|
||||
this.renderCancellationTokenSource = new CancellationTokenSource();
|
||||
this.renderThread = newRenderThread;
|
||||
this.renderSemaphore = new SemaphoreSlim(0, 1);
|
||||
this.isDynamicResolutionEnabled = isDynamicResolutionEnabled;
|
||||
this.isResizePending = true;
|
||||
|
||||
newRenderThread.Start(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.isDynamicResolutionEnabled = isDynamicResolutionEnabled;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues a change in the vertical sync mode.
|
||||
/// </summary>
|
||||
/// <param name="isVerticalSyncEnabled">Whether or not to use vertical sync.</param>
|
||||
public async void QueueVerticalSyncModeChange(bool isVerticalSyncEnabled)
|
||||
{
|
||||
using (await this.setupSemaphore.LockAsync())
|
||||
{
|
||||
// The v-sync option can be toggled on the fly when not using dynamic resolution
|
||||
if (this.renderCancellationTokenSource?.IsCancellationRequested == false &&
|
||||
this.isDynamicResolutionEnabled)
|
||||
{
|
||||
using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease();
|
||||
|
||||
this.renderCancellationTokenSource?.Cancel();
|
||||
|
||||
await this.renderSemaphore.WaitAsync();
|
||||
|
||||
Thread newRenderThread = new(static args => ((SwapChainManager<TOwner>)args!).SwitchAndStartRenderLoop());
|
||||
|
||||
this.renderCancellationTokenSource = new CancellationTokenSource();
|
||||
this.renderThread = newRenderThread;
|
||||
this.renderSemaphore = new SemaphoreSlim(0, 1);
|
||||
this.syncInterval = isVerticalSyncEnabled ? 1u : 0u;
|
||||
|
||||
newRenderThread.Start(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.syncInterval = isVerticalSyncEnabled ? 1u : 0u;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues a resize operation.
|
||||
/// </summary>
|
||||
/// <param name="width">The width of the render resolution.</param>
|
||||
/// <param name="height">The height of the render resolution.</param>
|
||||
public void QueueResize(double width, double height)
|
||||
{
|
||||
this.width = (float)width;
|
||||
this.height = (float)height;
|
||||
|
||||
this.isResizePending = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues a change in the composition scale factors.
|
||||
/// </summary>
|
||||
/// <param name="compositionScaleX">The composition scale on the X axis.</param>
|
||||
/// <param name="compositionScaleY">The composition scale on the Y axis</param>
|
||||
public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY)
|
||||
{
|
||||
this.compositionScaleX = (float)compositionScaleX;
|
||||
this.compositionScaleY = (float)compositionScaleY;
|
||||
|
||||
this.isResizePending = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues a change in the resolution scale factor.
|
||||
/// </summary>
|
||||
/// <param name="resolutionScale">The resolution scale factor to use.</param>
|
||||
public void QueueResolutionScaleChange(double resolutionScale)
|
||||
{
|
||||
this.resolutionScale = (float)resolutionScale;
|
||||
|
||||
this.isResizePending = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects the right render loop to start.
|
||||
/// </summary>
|
||||
private void SwitchAndStartRenderLoop()
|
||||
{
|
||||
try
|
||||
{
|
||||
OnRenderingStarted();
|
||||
|
||||
if (this.isDynamicResolutionEnabled)
|
||||
{
|
||||
this.dynamicResolutionScale = this.resolutionScale;
|
||||
|
||||
// These two leases are needed to ensure the manager isn't disposed while rendering is running
|
||||
using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease();
|
||||
|
||||
RenderLoopWithDynamicResolution();
|
||||
}
|
||||
else
|
||||
{
|
||||
using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease();
|
||||
|
||||
RenderLoop();
|
||||
}
|
||||
|
||||
this.renderStopwatch?.Stop();
|
||||
|
||||
OnRenderingStopped();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.renderStopwatch?.Stop();
|
||||
|
||||
OnRenderingFailed(e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_ = this.renderSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The core render loop.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private void RenderLoop()
|
||||
{
|
||||
Stopwatch renderStopwatch = this.renderStopwatch ??= new();
|
||||
CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token;
|
||||
|
||||
if (!OnFrameRequest(out object? parameter, cancellationToken))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
OnResize();
|
||||
|
||||
// Start the initial frame separately, before the timer starts. This ensures that
|
||||
// resuming after a pause correctly renders the first frame at the right time.
|
||||
if (OnUpdate(renderStopwatch.Elapsed, parameter))
|
||||
{
|
||||
OnWaitForPresent();
|
||||
OnPresent();
|
||||
}
|
||||
|
||||
renderStopwatch.Start();
|
||||
|
||||
// Main render loop, until cancellation is requested
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
if (!OnFrameRequest(out parameter, cancellationToken))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
OnResize();
|
||||
|
||||
if (OnUpdate(renderStopwatch.Elapsed, parameter))
|
||||
{
|
||||
OnWaitForPresent();
|
||||
OnPresent();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="DynamicResolutionManager"/> instance to use in <see cref="RenderLoopWithDynamicResolution"/>.
|
||||
/// </summary>
|
||||
/// <param name="resolutionManager">The <see cref="DynamicResolutionManager"/> instance to use.</param>
|
||||
private unsafe partial void OnGetDynamicResolutionManager(out DynamicResolutionManager resolutionManager);
|
||||
|
||||
/// <summary>
|
||||
/// The core render loop with dynamic resolution.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private unsafe void RenderLoopWithDynamicResolution()
|
||||
{
|
||||
Stopwatch renderStopwatch = this.renderStopwatch ??= new();
|
||||
Stopwatch frameStopwatch = new();
|
||||
CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token;
|
||||
|
||||
OnGetDynamicResolutionManager(out DynamicResolutionManager resolutionManager);
|
||||
|
||||
if (!OnFrameRequest(out object? parameter, cancellationToken))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
OnResize();
|
||||
|
||||
if (OnUpdate(renderStopwatch.Elapsed, parameter))
|
||||
{
|
||||
OnWaitForPresent();
|
||||
OnPresent();
|
||||
}
|
||||
|
||||
renderStopwatch.Start();
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
if (!OnFrameRequest(out parameter, cancellationToken))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
OnResize();
|
||||
|
||||
frameStopwatch.Restart();
|
||||
|
||||
if (OnUpdate(renderStopwatch.Elapsed, parameter))
|
||||
{
|
||||
frameStopwatch.Stop();
|
||||
|
||||
// The time spent waiting for present isn't included in the frame time, as when v-sync is
|
||||
// enabled it corresponds to the time spent waiting for the v-blank. If it was included,
|
||||
// then the actual framerate would never exceed the target one, meaning that if dynamic
|
||||
// resolution is enabled, the resolution scale could only keep decreasing without ever
|
||||
// being able to be increased again, as the framerate would never exceed the target.
|
||||
// Simply not counting the time spent waiting for that works around the issue.
|
||||
OnWaitForPresent();
|
||||
|
||||
frameStopwatch.Start();
|
||||
|
||||
OnPresent();
|
||||
|
||||
// Evaluate the dynamic resolution frame time step
|
||||
if (resolutionManager.Advance(frameStopwatch.ElapsedTicks, ref this.dynamicResolutionScale))
|
||||
{
|
||||
this.isResizePending = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for a new frame request and retrieves its parameter.
|
||||
/// </summary>
|
||||
/// <param name="parameter">The input parameter for the frame to render.</param>
|
||||
/// <param name="token">A token to cancel waiting for a new frame.</param>
|
||||
/// <returns>Whether the operation was canceled.</returns>
|
||||
private bool OnFrameRequest(out object? parameter, CancellationToken token)
|
||||
{
|
||||
if (this.frameRequestQueue is IFrameRequestQueue frameRequestQueue)
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static bool WaitForFrameRequest(IFrameRequestQueue frameRequestQueue, out object? parameter, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Wait for a new frame request
|
||||
frameRequestQueue.Dequeue(out parameter, token);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
parameter = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return WaitForFrameRequest(frameRequestQueue, out parameter, token);
|
||||
}
|
||||
|
||||
parameter = null;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resizes the current application, if needed.
|
||||
/// </summary>
|
||||
private void OnResize()
|
||||
{
|
||||
if (this.isResizePending)
|
||||
{
|
||||
ApplyResize();
|
||||
|
||||
this.isResizePending = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the render resolution, if needed, and renders a new frame.
|
||||
/// </summary>
|
||||
/// <param name="time">The current time since the start of the application.</param>
|
||||
/// <param name="parameter">The input parameter for the frame being rendered.</param>
|
||||
/// <returns>Whether or not to present the resulting frame.</returns>
|
||||
private bool OnUpdate(TimeSpan time, object? parameter)
|
||||
{
|
||||
return this.shaderRunner!.TryExecute(this.texture!, time, parameter);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the panel to be ready to present a new frame for the current application.
|
||||
/// </summary>
|
||||
private unsafe partial void OnWaitForPresent();
|
||||
|
||||
/// <summary>
|
||||
/// Presents the last rendered frame for the current application.
|
||||
/// </summary>
|
||||
private unsafe partial void OnPresent();
|
||||
|
||||
/// <summary>
|
||||
/// Raises <see cref="RenderingStarted"/>.
|
||||
/// </summary>
|
||||
private void OnRenderingStarted()
|
||||
{
|
||||
_ = this.dispatcherQueue.TryEnqueue(() => RenderingStarted?.Invoke(this.owner, EventArgs.Empty));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises <see cref="RenderingStopped"/>.
|
||||
/// </summary>
|
||||
private void OnRenderingStopped()
|
||||
{
|
||||
_ = this.dispatcherQueue.TryEnqueue(() => RenderingStopped?.Invoke(this.owner, EventArgs.Empty));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises <see cref="RenderingFailed"/>.
|
||||
/// </summary>
|
||||
/// <param name="e">The <see cref="Exception"/> being thrown that caused rendering to stop.</param>
|
||||
private void OnRenderingFailed(Exception e)
|
||||
{
|
||||
_ = this.dispatcherQueue.TryEnqueue(() => RenderingFailed?.Invoke(this.owner, new RenderingFailedEventArgs(e)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raises <see cref="Disposed"/>.
|
||||
/// </summary>
|
||||
private void OnDisposed()
|
||||
{
|
||||
_ = this.dispatcherQueue.TryEnqueue(() => Disposed?.Invoke(this.owner, EventArgs.Empty));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the current render loop, if one is running, and waits for it.
|
||||
/// </summary>
|
||||
/// <remarks>This method doesn't check for disposal.</remarks>
|
||||
private void UnsafeStopRenderLoopAndWait()
|
||||
{
|
||||
this.setupSemaphore.Wait();
|
||||
|
||||
this.renderCancellationTokenSource?.Cancel();
|
||||
this.renderSemaphore.Wait();
|
||||
}
|
||||
}
|
||||
@@ -1,584 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
#if WINDOWS_UWP
|
||||
using System.Runtime.InteropServices;
|
||||
#endif
|
||||
using System.Threading;
|
||||
using ComputeSharp.Core.Extensions;
|
||||
using ComputeSharp.Graphics.Helpers;
|
||||
using ComputeSharp.Interop;
|
||||
#if WINDOWS_UWP
|
||||
using ComputeSharp.Uwp.Extensions;
|
||||
#else
|
||||
using ComputeSharp.WinUI.Extensions;
|
||||
#endif
|
||||
#if !WINDOWS_UWP
|
||||
using Microsoft.UI.Dispatching;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
#endif
|
||||
using TerraFX.Interop.DirectX;
|
||||
using TerraFX.Interop.Windows;
|
||||
using TerraFX.Interop.WinRT;
|
||||
#if WINDOWS_UWP
|
||||
using Windows.Foundation;
|
||||
using Windows.UI.Xaml.Controls;
|
||||
using Windows.System;
|
||||
#else
|
||||
using Windows.Foundation;
|
||||
using WinRT;
|
||||
#endif
|
||||
using Win32 = TerraFX.Interop.Windows.Windows;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp.Helpers;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI.Helpers;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A type managing rendering on a target swap chain object.
|
||||
/// </summary>
|
||||
/// <typeparam name="TOwner">The type of the owner <see cref="SwapChainPanel"/> instance.</typeparam>
|
||||
internal sealed unsafe partial class SwapChainManager<TOwner> : ReferenceTrackedObject
|
||||
where TOwner : SwapChainPanel
|
||||
{
|
||||
/// <summary>
|
||||
/// The owning <typeparamref name="TOwner"/> instance.
|
||||
/// </summary>
|
||||
private readonly TOwner owner;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="GraphicsDevice"/> instance in use.
|
||||
/// </summary>
|
||||
private readonly GraphicsDevice device;
|
||||
|
||||
/// <summary>
|
||||
/// The captured <see cref="SynchronizationContext"/> for the current instance.
|
||||
/// </summary>
|
||||
private readonly DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();
|
||||
|
||||
/// <summary>
|
||||
/// An <see cref="SemaphoreSlim"/> object for the render loop management.
|
||||
/// </summary>
|
||||
private readonly SemaphoreSlim setupSemaphore = new(1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="ID3D12Device"/> pointer for the device currently in use.
|
||||
/// </summary>
|
||||
private ComPtr<ID3D12Device> d3D12Device;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="ID3D12CommandQueue"/> instance to use for graphics operations.
|
||||
/// </summary>
|
||||
private ComPtr<ID3D12CommandQueue> d3D12CommandQueue;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="ID3D12Fence"/> instance used for graphics operations.
|
||||
/// </summary>
|
||||
private ComPtr<ID3D12Fence> d3D12Fence;
|
||||
|
||||
/// <summary>
|
||||
/// The next fence value for graphics operations using <see cref="d3D12CommandQueue"/>.
|
||||
/// </summary>
|
||||
private ulong nextD3D12FenceValue;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="ID3D12CommandAllocator"/> object to create command lists.
|
||||
/// </summary>
|
||||
private ComPtr<ID3D12CommandAllocator> d3D12CommandAllocator;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="ID3D12GraphicsCommandList"/> instance used to copy data to the back buffers.
|
||||
/// </summary>
|
||||
private ComPtr<ID3D12GraphicsCommandList> d3D12GraphicsCommandList;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="ISwapChainPanelNative"/> instance for the underlying object wrapped by the target control.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is needed to call <see cref="ISwapChainPanelNative.SetSwapChain(IDXGISwapChain*)"/> with <see langword="null"/>
|
||||
/// when the panel is destroyed, so the additional implicit references to the swap chain an native device can be released.
|
||||
/// </remarks>
|
||||
private ComPtr<ISwapChainPanelNative> swapChainPanelNative;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="IDXGISwapChain3"/> instance used to display content onto the target window.
|
||||
/// </summary>
|
||||
private ComPtr<IDXGISwapChain3> dxgiSwapChain3;
|
||||
|
||||
/// <summary>
|
||||
/// The awaitable object for <see cref="IDXGISwapChain3.Present"/> calls.
|
||||
/// </summary>
|
||||
private readonly HANDLE frameLatencyWaitableObject;
|
||||
|
||||
/// <summary>
|
||||
/// The first buffer within <see cref="dxgiSwapChain3"/>.
|
||||
/// </summary>
|
||||
private ComPtr<ID3D12Resource> d3D12Resource0;
|
||||
|
||||
/// <summary>
|
||||
/// The second buffer within <see cref="dxgiSwapChain3"/>.
|
||||
/// </summary>
|
||||
private ComPtr<ID3D12Resource> d3D12Resource1;
|
||||
|
||||
/// <summary>
|
||||
/// The index of the next buffer that can be used to present content.
|
||||
/// </summary>
|
||||
private volatile uint currentBufferIndex;
|
||||
|
||||
/// <summary>
|
||||
/// The render thread in use, if any.
|
||||
/// </summary>
|
||||
private volatile Thread? renderThread;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="SemaphoreSlim"/> used to wait for render threads to complete.
|
||||
/// </summary>
|
||||
private volatile SemaphoreSlim renderSemaphore = new(1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="CancellationTokenSource"/> to use for <see cref="renderThread"/>.
|
||||
/// </summary>
|
||||
private volatile CancellationTokenSource? renderCancellationTokenSource;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="IFrameRequestQueue"/> instance used to get frame requests and parameters.
|
||||
/// </summary>
|
||||
private volatile IFrameRequestQueue? frameRequestQueue;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="IShaderRunner"/> instance used to create shaders to run.
|
||||
/// </summary>
|
||||
private volatile IShaderRunner? shaderRunner;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="ReadWriteTexture2D{T, TPixel}"/> instance used to prepare frames to display.
|
||||
/// </summary>
|
||||
private volatile ReadWriteTexture2D<Rgba32, Float4>? texture;
|
||||
|
||||
/// <summary>
|
||||
/// Whether or not the window has been resized and requires the buffers to be updated.
|
||||
/// </summary>
|
||||
private volatile bool isResizePending;
|
||||
|
||||
/// <summary>
|
||||
/// The backing store for the actual width for the render thread.
|
||||
/// </summary>
|
||||
private volatile float width;
|
||||
|
||||
/// <summary>
|
||||
/// The backing store for the actual height for the render thread.
|
||||
/// </summary>
|
||||
private volatile float height;
|
||||
|
||||
/// <summary>
|
||||
/// The backing store for the current composition scale on the X axis for the render thread.
|
||||
/// </summary>
|
||||
private volatile float compositionScaleX;
|
||||
|
||||
/// <summary>
|
||||
/// The backing store for the current composition scale on the Y axis for the render thread.
|
||||
/// </summary>
|
||||
private volatile float compositionScaleY;
|
||||
|
||||
/// <summary>
|
||||
/// The resolution scale used to render frames when explicitly controlled by the user.
|
||||
/// </summary>
|
||||
private volatile float resolutionScale;
|
||||
|
||||
/// <summary>
|
||||
/// The dynamic resolution scale used to render frames.
|
||||
/// </summary>
|
||||
private volatile float dynamicResolutionScale;
|
||||
|
||||
/// <summary>
|
||||
/// Whether dynamic resolution is currently enabled.
|
||||
/// </summary>
|
||||
private volatile bool isDynamicResolutionEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// The flags to enable or disable vertical sync.
|
||||
/// </summary>
|
||||
private volatile uint syncInterval;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="Stopwatch"/> instance tracking time since the first rendered frame.
|
||||
/// </summary>
|
||||
private volatile Stopwatch? renderStopwatch;
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever rendering starts.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<TOwner, EventArgs>? RenderingStarted;
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever rendering stops.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<TOwner, EventArgs>? RenderingStopped;
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever rendering fails.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<TOwner, RenderingFailedEventArgs>? RenderingFailed;
|
||||
|
||||
/// <summary>
|
||||
/// Raised whenever the parent control is disposed and all underlying resources are released.
|
||||
/// </summary>
|
||||
public event TypedEventHandler<TOwner, EventArgs>? Disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SwapChainManager{TOwner}"/> type.
|
||||
/// </summary>
|
||||
/// <param name="owner">The input swap chain instance being used.</param>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to render frames.</param>
|
||||
public SwapChainManager(TOwner owner, GraphicsDevice device)
|
||||
{
|
||||
this.owner = owner;
|
||||
this.device = device;
|
||||
|
||||
// Extract the ISwapChainPanelNative reference from the current panel, then query the
|
||||
// IDXGISwapChain reference just created and set that as the swap chain panel to use.
|
||||
fixed (ISwapChainPanelNative** swapChainPanelNative = this.swapChainPanelNative)
|
||||
{
|
||||
using ComPtr<IUnknown> swapChainPanel = default;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
swapChainPanel.Attach((IUnknown*)Marshal.GetIUnknownForObject(owner));
|
||||
|
||||
swapChainPanel.CopyTo(swapChainPanelNative).Assert();
|
||||
#else
|
||||
swapChainPanel.Attach((IUnknown*)((IWinRTObject)owner).NativeObject.GetRef());
|
||||
|
||||
swapChainPanel.CopyTo(
|
||||
(Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(new Guid(0x63AAD0B8, 0x7C24, 0x40FF, 0x85, 0xA8, 0x64, 0x0D, 0x94, 0x4C, 0xC3, 0x25))),
|
||||
(void**)swapChainPanelNative).Assert();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Get the underlying ID3D12Device in use
|
||||
fixed (ID3D12Device** d3D12Device = this.d3D12Device)
|
||||
{
|
||||
this.device.D3D12Device->QueryInterface(Win32.__uuidof<ID3D12Device>(), (void**)d3D12Device).Assert();
|
||||
}
|
||||
|
||||
// Create the direct command queue to use
|
||||
fixed (ID3D12CommandQueue** d3D12CommandQueue = this.d3D12CommandQueue)
|
||||
{
|
||||
D3D12_COMMAND_QUEUE_DESC d3D12CommandQueueDesc;
|
||||
d3D12CommandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
d3D12CommandQueueDesc.Priority = (int)D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
|
||||
d3D12CommandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAGS.D3D12_COMMAND_QUEUE_FLAG_NONE;
|
||||
d3D12CommandQueueDesc.NodeMask = 0;
|
||||
|
||||
this.d3D12Device.Get()->CreateCommandQueue(
|
||||
&d3D12CommandQueueDesc,
|
||||
Win32.__uuidof<ID3D12CommandQueue>(),
|
||||
(void**)d3D12CommandQueue).Assert();
|
||||
}
|
||||
|
||||
// Create the direct fence
|
||||
fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence)
|
||||
{
|
||||
this.d3D12Device.Get()->CreateFence(
|
||||
0,
|
||||
D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE,
|
||||
Win32.__uuidof<ID3D12Fence>(),
|
||||
(void**)d3D12Fence).Assert();
|
||||
}
|
||||
|
||||
// Create the swap chain to display frames
|
||||
using (ComPtr<IDXGIFactory6> dxgiFactory6 = default)
|
||||
{
|
||||
DeviceHelper.CreateDXGIFactory6(dxgiFactory6.GetAddressOf());
|
||||
|
||||
DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default;
|
||||
dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE;
|
||||
dxgiSwapChainDesc1.BufferCount = 2;
|
||||
dxgiSwapChainDesc1.Flags = (uint)DXGI_SWAP_CHAIN_FLAG.DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
|
||||
dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_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;
|
||||
dxgiSwapChainDesc1.BufferUsage = DXGI.DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
|
||||
using ComPtr<IDXGISwapChain1> dxgiSwapChain1 = default;
|
||||
|
||||
dxgiFactory6.Get()->CreateSwapChainForComposition(
|
||||
(IUnknown*)this.d3D12CommandQueue.Get(),
|
||||
&dxgiSwapChainDesc1,
|
||||
null,
|
||||
(IDXGISwapChain1**)&dxgiSwapChain1).Assert();
|
||||
|
||||
fixed (IDXGISwapChain3** dxgiSwapChain3 = this.dxgiSwapChain3)
|
||||
{
|
||||
dxgiSwapChain1.CopyTo(dxgiSwapChain3).Assert();
|
||||
}
|
||||
}
|
||||
|
||||
// Get the awaitable object to synchronizize present calls
|
||||
this.frameLatencyWaitableObject = this.dxgiSwapChain3.Get()->GetFrameLatencyWaitableObject();
|
||||
|
||||
// Create the command allocator to use
|
||||
fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator)
|
||||
{
|
||||
this.d3D12Device.Get()->CreateCommandAllocator(
|
||||
D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
Win32.__uuidof<ID3D12CommandAllocator>(),
|
||||
(void**)d3D12CommandAllocator).Assert();
|
||||
}
|
||||
|
||||
// Create the reusable command list to copy data to the back buffers
|
||||
fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList)
|
||||
{
|
||||
this.d3D12Device.Get()->CreateCommandList(
|
||||
0,
|
||||
D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
this.d3D12CommandAllocator.Get(),
|
||||
null,
|
||||
Win32.__uuidof<ID3D12GraphicsCommandList>(),
|
||||
(void**)d3D12GraphicsCommandList).Assert();
|
||||
}
|
||||
|
||||
// Close the command list to prepare it for future use
|
||||
this.d3D12GraphicsCommandList.Get()->Close().Assert();
|
||||
|
||||
using (ComPtr<IDXGISwapChain> idxgiSwapChain = default)
|
||||
{
|
||||
this.dxgiSwapChain3.CopyTo(idxgiSwapChain.GetAddressOf()).Assert();
|
||||
|
||||
this.swapChainPanelNative.Get()->SetSwapChain(idxgiSwapChain.Get()).Assert();
|
||||
}
|
||||
|
||||
GC.KeepAlive(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the actual resize logic that was scheduled from <see cref="OnResize"/>, if needed.
|
||||
/// </summary>
|
||||
private unsafe void ApplyResize()
|
||||
{
|
||||
// The target resolution scale is either the dynamic resolution scale, being updated by the render thread,
|
||||
// or the fixed resolution scale set by the user. If dynamic resolution is enabled, the latter is ignored.
|
||||
float targetResolutionScale = this.isDynamicResolutionEnabled
|
||||
? this.dynamicResolutionScale
|
||||
: this.resolutionScale;
|
||||
|
||||
uint resizedWidth = (uint)Math.Max(Math.Ceiling(this.width * this.compositionScaleX * targetResolutionScale), 1.0);
|
||||
uint resizeHeight = (uint)Math.Max(Math.Ceiling(this.height * this.compositionScaleY * targetResolutionScale), 1.0);
|
||||
|
||||
if (this.texture is null ||
|
||||
this.texture.Width != resizedWidth ||
|
||||
this.texture.Height != resizeHeight)
|
||||
{
|
||||
ulong updatedFenceValue = ++this.nextD3D12FenceValue;
|
||||
|
||||
this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), updatedFenceValue).Assert();
|
||||
|
||||
// Wait for the fence again to ensure there are no pending operations
|
||||
this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert();
|
||||
|
||||
// Dispose the old buffers before resizing the buffer
|
||||
this.d3D12Resource0.Dispose();
|
||||
this.d3D12Resource1.Dispose();
|
||||
|
||||
// Resize the swap chain buffers
|
||||
this.dxgiSwapChain3.Get()->ResizeBuffers(
|
||||
2,
|
||||
resizedWidth,
|
||||
resizeHeight,
|
||||
DXGI_FORMAT.DXGI_FORMAT_UNKNOWN,
|
||||
(uint)DXGI_SWAP_CHAIN_FLAG.DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT).Assert();
|
||||
|
||||
// Apply the necessary scale transform
|
||||
DXGI_MATRIX_3X2_F transformMatrix = default;
|
||||
transformMatrix._11 = 1 / this.compositionScaleX * (1 / targetResolutionScale);
|
||||
transformMatrix._22 = 1 / this.compositionScaleY * (1 / targetResolutionScale);
|
||||
|
||||
this.dxgiSwapChain3.Get()->SetMatrixTransform(&transformMatrix).Assert();
|
||||
|
||||
// Retrieve the back buffers for the swap chain
|
||||
fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0)
|
||||
fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1)
|
||||
{
|
||||
this.dxgiSwapChain3.Get()->GetBuffer(0, Win32.__uuidof<ID3D12Resource>(), (void**)d3D12Resource0).Assert();
|
||||
this.dxgiSwapChain3.Get()->GetBuffer(1, Win32.__uuidof<ID3D12Resource>(), (void**)d3D12Resource1).Assert();
|
||||
}
|
||||
|
||||
// Get the index of the initial back buffer
|
||||
this.currentBufferIndex = this.dxgiSwapChain3.Get()->GetCurrentBackBufferIndex();
|
||||
|
||||
// Dispose the previous texture, if present, and create the new 2D texture to use to generate frames to display
|
||||
this.texture?.Dispose();
|
||||
|
||||
this.texture = this.device.AllocateReadWriteTexture2D<Rgba32, Float4>((int)resizedWidth, (int)resizeHeight);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private unsafe partial void OnWaitForPresent()
|
||||
{
|
||||
_ = Win32.WaitForSingleObjectEx(this.frameLatencyWaitableObject, Win32.INFINITE, true);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private unsafe partial void OnPresent()
|
||||
{
|
||||
using ComPtr<ID3D12Resource> d3D12Resource = default;
|
||||
|
||||
// Get the underlying ID3D12Resource pointer for the texture
|
||||
this.texture!.D3D12Resource->QueryInterface(Win32.__uuidof<ID3D12Resource>(), (void**)d3D12Resource.GetAddressOf()).Assert();
|
||||
|
||||
// Get the target back buffer to update
|
||||
ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch
|
||||
{
|
||||
0 => this.d3D12Resource0.Get(),
|
||||
1 => this.d3D12Resource1.Get(),
|
||||
_ => null
|
||||
};
|
||||
|
||||
this.currentBufferIndex ^= 1;
|
||||
|
||||
// Reset the command list and command allocator
|
||||
this.d3D12CommandAllocator.Get()->Reset().Assert();
|
||||
this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null).Assert();
|
||||
|
||||
D3D12_RESOURCE_BARRIER* d3D12ResourceBarriers = stackalloc D3D12_RESOURCE_BARRIER[]
|
||||
{
|
||||
D3D12_RESOURCE_BARRIER.InitTransition(
|
||||
d3D12Resource.Get(),
|
||||
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
|
||||
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE),
|
||||
D3D12_RESOURCE_BARRIER.InitTransition(
|
||||
d3D12ResourceBackBuffer,
|
||||
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON,
|
||||
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST)
|
||||
};
|
||||
|
||||
// Transition the resources to COPY_DEST and COPY_SOURCE respectively
|
||||
this.d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
|
||||
|
||||
// Copy the generated frame to the target back buffer
|
||||
this.d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get());
|
||||
|
||||
d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition(
|
||||
d3D12Resource.Get(),
|
||||
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE,
|
||||
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
|
||||
|
||||
d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition(
|
||||
d3D12ResourceBackBuffer,
|
||||
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON);
|
||||
|
||||
// Transition the resources back to COMMON and UNORDERED_ACCESS respectively
|
||||
this.d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
|
||||
|
||||
this.d3D12GraphicsCommandList.Get()->Close().Assert();
|
||||
|
||||
// Execute the command list to perform the copy
|
||||
fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList)
|
||||
{
|
||||
this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList);
|
||||
}
|
||||
|
||||
// Increment the fence value and signal the fence. Just like with normal dispatches,
|
||||
// the increment must be done after executing the command list and before signaling.
|
||||
ulong updatedFenceValue = ++this.nextD3D12FenceValue;
|
||||
|
||||
this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), updatedFenceValue).Assert();
|
||||
|
||||
// Present the new frame
|
||||
this.dxgiSwapChain3.Get()->Present(SyncInterval: this.syncInterval, 0).Assert();
|
||||
|
||||
if (updatedFenceValue > this.d3D12Fence.Get()->GetCompletedValue())
|
||||
{
|
||||
this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
private unsafe partial void OnGetDynamicResolutionManager(out DynamicResolutionManager resolutionManager)
|
||||
{
|
||||
using ComPtr<IDXGIFactory6> dxgiFactory6 = default;
|
||||
|
||||
DeviceHelper.CreateDXGIFactory6(dxgiFactory6.GetAddressOf());
|
||||
|
||||
using ComPtr<IDXGIAdapter> dxgiAdapter = default;
|
||||
|
||||
dxgiFactory6.Get()->EnumAdapters(0, dxgiAdapter.GetAddressOf()).Assert();
|
||||
|
||||
int targetFramerate = dxgiAdapter.Get()->GetCompositionRefreshRate(DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM);
|
||||
|
||||
resolutionManager = new DynamicResolutionManager(targetFramerate);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override void DangerousOnDispose()
|
||||
{
|
||||
static void OnDisposeOnDispatcherQueueThread(SwapChainManager<TOwner> @this)
|
||||
{
|
||||
// Even while rendering is still running, we need to properly release all implicit references
|
||||
// that have been added when connecting the swap chain panel that was used. To do that, the
|
||||
// same ISwapChainPanelNative::SetSwapChain API has to be called, but passing null as the
|
||||
// target swap chain. This is handled correctly in the implementation, and all the additional
|
||||
// references to the swap chain we passed during initialization will be dropped. Once that
|
||||
// is done, we can then dispose our reference to the underlying swap chain panel for the control.
|
||||
// This API has to be called on the UI thread, and it can be called just fine even if rendering
|
||||
// is still running, so we can just call it immediately before moving to a thread to stop rendering.
|
||||
@this.swapChainPanelNative.Get()->SetSwapChain(null).Assert();
|
||||
@this.swapChainPanelNative.Dispose();
|
||||
|
||||
_ = ThreadPool.UnsafeQueueUserWorkItem(static state =>
|
||||
{
|
||||
SwapChainManager<TOwner> @this = (SwapChainManager<TOwner>)state!;
|
||||
|
||||
@this.UnsafeStopRenderLoopAndWait();
|
||||
|
||||
ulong updatedFenceValue = @this.nextD3D12FenceValue + 1;
|
||||
|
||||
@this.d3D12CommandQueue.Get()->Signal(@this.d3D12Fence.Get(), updatedFenceValue).Assert();
|
||||
|
||||
// Just like in the resize logic, signal and wait to make sure no operations are pending. This
|
||||
// is needed to avoid a crash when disposing resources when disposing after stopping rendering.
|
||||
@this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert();
|
||||
|
||||
_ = Win32.CloseHandle(@this.frameLatencyWaitableObject);
|
||||
|
||||
@this.d3D12Device.Dispose();
|
||||
@this.d3D12CommandQueue.Dispose();
|
||||
@this.d3D12Fence.Dispose();
|
||||
@this.d3D12CommandAllocator.Dispose();
|
||||
@this.d3D12GraphicsCommandList.Dispose();
|
||||
@this.dxgiSwapChain3.Dispose();
|
||||
@this.d3D12Resource0.Dispose();
|
||||
@this.d3D12Resource1.Dispose();
|
||||
@this.texture?.Dispose();
|
||||
|
||||
@this.OnDisposed();
|
||||
}, @this);
|
||||
}
|
||||
|
||||
// Check whether the current thread is the one associated with the dispatcher queue. If so, the dispose
|
||||
// logic can be called directly, otherwise an extra dispatch is needed. This is because the start of
|
||||
// the dispose logic requires UI thread access to interact with the swap chain panel.
|
||||
if (this.dispatcherQueue.HasThreadAccess)
|
||||
{
|
||||
OnDisposeOnDispatcherQueueThread(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static void OnDisposeOnThreadPoolThread(SwapChainManager<TOwner> @this)
|
||||
{
|
||||
_ = @this.dispatcherQueue.TryEnqueue(() => OnDisposeOnDispatcherQueueThread(@this));
|
||||
}
|
||||
|
||||
// Move to a separate queue to skip the closure when lowering this method, if not needed
|
||||
OnDisposeOnThreadPoolThread(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
using System.Threading;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// An interface for a shader runner to be used with <see cref="ComputeShaderPanel"/>.
|
||||
/// </summary>
|
||||
public interface IFrameRequestQueue
|
||||
{
|
||||
/// <summary>
|
||||
/// Waits for a new frame request to be available, retrieving its parameter, if any.
|
||||
/// </summary>
|
||||
/// <param name="parameter">The input parameter for the frame to render.</param>
|
||||
/// <param name="token">A token to cancel waiting for a new frame.</param>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This method should block synchronously until a new frame is available, returning its
|
||||
/// parameters if any. The <paramref name="token"/> parameter should be used to cancel a
|
||||
/// blocking operation and return immediately, as it's cancelled when rendering is stopped.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// For instance, if the <see cref="IFrameRequestQueue"/> implementation is internally using a
|
||||
/// <see cref="System.Collections.Concurrent.BlockingCollection{T}"/> queue and calling
|
||||
/// <see cref="System.Collections.Concurrent.BlockingCollection{T}.Take()"/> to block and wait for
|
||||
/// a new frame parameter, the <see cref="System.Collections.Concurrent.BlockingCollection{T}.Take(CancellationToken)"/>
|
||||
/// overload should be used instead, to enable canceling the operation early if needed.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If the runner throws an <see cref="System.OperationCanceledException"/>, this will just be recognized by the
|
||||
/// <see cref="ComputeShaderPanel"/> in use and result in rendering simply being stopped. If any other exceptions are thrown
|
||||
/// instead, they will be interpreted as a failure, and <see cref="ComputeShaderPanel.RenderingFailed"/> will be raised.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
void Dequeue(out object? parameter, CancellationToken token);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
using System;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// An interface for a shader runner to be used with <see cref="ComputeShaderPanel"/> or <see cref="AnimatedComputeShaderPanel"/>.
|
||||
/// </summary>
|
||||
public interface IShaderRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Tries to render a single frame to a texture, optionally skipping the frame if needed.
|
||||
/// </summary>
|
||||
/// <param name="texture">The target texture to render the frame to.</param>
|
||||
/// <param name="timespan">The timespan for the current frame.</param>
|
||||
/// <param name="parameter">The input parameter for the frame being rendered.</param>
|
||||
/// <returns>Whether or not to present the current frame. If <see langword="false"/>, the frame will be skipped.</returns>
|
||||
/// <remarks>
|
||||
/// Any exceptions thrown by the runner will result in <see cref="ComputeShaderPanel.RenderingFailed"/>
|
||||
/// or <see cref="AnimatedComputeShaderPanel.RenderingFailed"/> to be raised.
|
||||
/// </remarks>
|
||||
bool TryExecute(IReadWriteNormalizedTexture2D<Float4> texture, TimeSpan timespan, object? parameter);
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
using System;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
namespace ComputeSharp.Uwp;
|
||||
#else
|
||||
namespace ComputeSharp.WinUI;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// A simple <see cref="IShaderRunner"/> implementation powered by a supplied shader type.
|
||||
/// All rendered frames produced by this type will always be presented.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of shader to use to render frames.</typeparam>
|
||||
public sealed class ShaderRunner<T> : IShaderRunner
|
||||
where T : struct, IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="Func{T1,TResult}"/> instance used to create shaders to run.
|
||||
/// </summary>
|
||||
private readonly Func<TimeSpan, T>? shaderFactory;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="Func{T1,T2,TResult}"/> instance used to create shaders to run.
|
||||
/// </summary>
|
||||
private readonly Func<TimeSpan, object?, T>? statefulShaderFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderRunner{T}"/> instance that will create shader instances with
|
||||
/// the default constructor. Only use this constructor if the shader doesn't require any additional
|
||||
/// resources or other parameters being initialized before being dispatched on the GPU.
|
||||
/// </summary>
|
||||
public ShaderRunner()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderRunner{T}"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="shaderFactory">The <see cref="Func{T1,TResult}"/> instance used to create shaders to run.</param>
|
||||
public ShaderRunner(Func<TimeSpan, T> shaderFactory)
|
||||
{
|
||||
default(ArgumentNullException).ThrowIfNull(shaderFactory);
|
||||
|
||||
this.shaderFactory = shaderFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ShaderRunner{T}"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="shaderFactory">The <see cref="Func{T1,T2,TResult}"/> instance used to create shaders to run.</param>
|
||||
public ShaderRunner(Func<TimeSpan, object?, T> shaderFactory)
|
||||
{
|
||||
default(ArgumentNullException).ThrowIfNull(shaderFactory);
|
||||
|
||||
this.statefulShaderFactory = shaderFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool TryExecute(IReadWriteNormalizedTexture2D<Float4> texture, TimeSpan time, object? parameter)
|
||||
{
|
||||
if (this.shaderFactory is Func<TimeSpan, T> shaderFactory)
|
||||
{
|
||||
texture.GraphicsDevice.ForEach(texture, this.shaderFactory(time));
|
||||
}
|
||||
else
|
||||
{
|
||||
texture.GraphicsDevice.ForEach(texture, this.statefulShaderFactory!(time, parameter));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする