diff --git a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs index a3d18eb4..2aa1a353 100644 --- a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs +++ b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/ContouredLayersRunner.cs @@ -23,7 +23,7 @@ public sealed class ContouredLayersRunner : IShaderRunner private ReadOnlyTexture2D? texture; /// - public void Execute(IReadWriteTexture2D texture, TimeSpan timespan) + public void Execute(IReadWriteTexture2D texture, TimeSpan timespan, object? parameter) { if (this.texture is null) { diff --git a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj index c183283c..477be62b 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj +++ b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj @@ -123,6 +123,7 @@ App.xaml + MainView.xaml diff --git a/samples/ComputeSharp.SwapChain.Uwp/Properties/AssemblyInfo.cs b/samples/ComputeSharp.SwapChain.Uwp/Properties/AssemblyInfo.cs index c199ce78..0ed0ddff 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/Properties/AssemblyInfo.cs +++ b/samples/ComputeSharp.SwapChain.Uwp/Properties/AssemblyInfo.cs @@ -1,4 +1,5 @@ using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -25,4 +26,6 @@ using System.Runtime.InteropServices; // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] -[assembly: ComVisible(false)] \ No newline at end of file +[assembly: ComVisible(false)] + +[module: SkipLocalsInit] \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.Uwp/Properties/SkipLocalsInitAttribute.cs b/samples/ComputeSharp.SwapChain.Uwp/Properties/SkipLocalsInitAttribute.cs new file mode 100644 index 00000000..894d04db --- /dev/null +++ b/samples/ComputeSharp.SwapChain.Uwp/Properties/SkipLocalsInitAttribute.cs @@ -0,0 +1,16 @@ +namespace System.Runtime.CompilerServices; + +/// +/// Used to indicate to the compiler that the .locals init flag should not be set in method headers. +/// +[AttributeUsage(AttributeTargets.Module + | AttributeTargets.Class + | AttributeTargets.Struct + | AttributeTargets.Interface + | AttributeTargets.Constructor + | AttributeTargets.Method + | AttributeTargets.Property + | AttributeTargets.Event, Inherited = false)] +internal sealed class SkipLocalsInitAttribute : Attribute +{ +} \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml b/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml index fe94efd1..5b07b170 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml +++ b/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml @@ -125,7 +125,7 @@ - + - - + - ComputeSharp.UI + + - + + + + diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs new file mode 100644 index 00000000..6e5bc36e --- /dev/null +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.Properties.cs @@ -0,0 +1,172 @@ +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 + +/// +partial class AnimatedComputeShaderPanel +{ + /// + /// Raised whenever rendering starts. + /// + public event TypedEventHandler? RenderingStarted + { + add => this.swapChainManager.RenderingStarted += value; + remove => this.swapChainManager.RenderingStarted -= value; + } + + /// + /// Raised whenever rendering stops. + /// + public event TypedEventHandler? RenderingStopped + { + add => this.swapChainManager.RenderingStopped += value; + remove => this.swapChainManager.RenderingStopped -= value; + } + + /// + /// Raised whenever rendering fails. + /// + public event TypedEventHandler? RenderingFailed + { + add => this.swapChainManager.RenderingFailed += value; + remove => this.swapChainManager.RenderingFailed -= value; + } + + /// + /// Gets or sets the instance to use to render content. + /// + public IShaderRunner? ShaderRunner + { + get => (IShaderRunner?)GetValue(ShaderRunnerProperty); + set => SetValue(ShaderRunnerProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty ShaderRunnerProperty = DependencyProperty.Register( + nameof(ShaderRunner), + typeof(IShaderRunner), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(null, OnShaderRunnerPropertyChanged)); + + /// + private static void OnShaderRunnerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (AnimatedComputeShaderPanel)d; + + if (@this.IsLoaded && + !@this.IsPaused && + e.NewValue is IShaderRunner shaderRunner) + { + @this.swapChainManager.StartRenderLoop(null, shaderRunner); + } + else + { + @this.swapChainManager.StopRenderLoop(); + } + } + + /// + /// Gets or sets the resolution scale to be used to render frames. + /// This can help achieve higher framerates with more complex shaders. + /// + /// The accepted range is [0.1 and 1] (default is 1, exceeding values will be clamped). + public double ResolutionScale + { + get => (double)GetValue(ResolutionScaleProperty); + set => SetValue(ResolutionScaleProperty, Math.Clamp(value, 0.1, 1.0)); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty ResolutionScaleProperty = DependencyProperty.Register( + nameof(ResolutionScale), + typeof(double), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(1.0, OnResolutionScalePropertyChanged)); + + /// + private static void OnResolutionScalePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (AnimatedComputeShaderPanel)d; + var resolutionScale = (double)e.NewValue; + + @this.swapChainManager.QueueResolutionScaleChange(resolutionScale); + } + + /// + /// 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. + /// The default value for this property is . + /// + public bool IsDynamicResolutionEnabled + { + get => (bool)GetValue(IsDynamicResolutionEnabledProperty); + set => SetValue(IsDynamicResolutionEnabledProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty IsDynamicResolutionEnabledProperty = DependencyProperty.Register( + nameof(IsDynamicResolutionEnabled), + typeof(bool), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(true, OnIsDynamicResolutionEnabledPropertyChanged)); + + /// + private static void OnIsDynamicResolutionEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (AnimatedComputeShaderPanel)d; + var isDynamicResolutionEnabled = (bool)e.NewValue; + + @this.swapChainManager.QueueDynamicResolutionModeChange(isDynamicResolutionEnabled); + } + + /// + /// Gets or sets whether or not the rendering is paused. + /// + public bool IsPaused + { + get => (bool)GetValue(IsPausedProperty); + set => SetValue(IsPausedProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty IsPausedProperty = DependencyProperty.Register( + nameof(IsPaused), + typeof(bool), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(false, OnIsPausedPropertyChanged)); + + /// + private static void OnIsPausedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @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(); + } + } +} diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs new file mode 100644 index 00000000..27b77bc1 --- /dev/null +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs @@ -0,0 +1,78 @@ +#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 + +/// +/// +/// A custom that can be used to render animated backgrounds. +/// It is powered by ComputeSharp and leverages compute shaders to create frames to display. +/// +/// +/// This panel will always render new frames at the current display refresh rate, automatically. +/// +/// +public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel +{ + /// + /// The instance handling rendering. + /// + private readonly SwapChainManager swapChainManager; + + /// + /// Creates a new instance. + /// + public unsafe AnimatedComputeShaderPanel() + { + this.swapChainManager = new SwapChainManager(this); + + this.Loaded += AnimatedComputeShaderPanel_Loaded; + this.Unloaded += AnimatedComputeShaderPanel_Unloaded; + this.SizeChanged += AnimatedComputeShaderPanel_SizeChanged; + this.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); + + 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); + } +} diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 73e49028..7e351bc0 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -1,34 +1,116 @@ 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 - -using Microsoft.UI.Xaml; namespace ComputeSharp.WinUI; #endif /// -public sealed unsafe partial class ComputeShaderPanel +partial class ComputeShaderPanel { /// - /// Gets or sets the instance to use to render content. + /// Raised whenever rendering starts. /// - public IShaderRunner? ShaderRunner + public event TypedEventHandler? RenderingStarted { - get => (IShaderRunner?)GetValue(ShaderFactoryProperty); - set => SetValue(ShaderFactoryProperty, value); + add => this.swapChainManager.RenderingStarted += value; + remove => this.swapChainManager.RenderingStarted -= value; + } + + /// + /// Raised whenever rendering stops. + /// + public event TypedEventHandler? RenderingStopped + { + add => this.swapChainManager.RenderingStopped += value; + remove => this.swapChainManager.RenderingStopped -= value; + } + + /// + /// Raised whenever rendering fails. + /// + public event TypedEventHandler? RenderingFailed + { + add => this.swapChainManager.RenderingFailed += value; + remove => this.swapChainManager.RenderingFailed -= value; + } + + /// + /// Gets or sets the instance to use to request new frames. + /// + public IFrameRequestQueue? FrameRequestQueue + { + get => (IFrameRequestQueue)GetValue(FrameRequestQueueProperty); + set => SetValue(FrameRequestQueueProperty, value); } /// /// The backing . /// - public static readonly DependencyProperty ShaderFactoryProperty = DependencyProperty.Register( + public static readonly DependencyProperty FrameRequestQueueProperty = DependencyProperty.Register( + nameof(FrameRequestQueue), + typeof(IFrameRequestQueue), + typeof(ComputeShaderPanel), + new PropertyMetadata(null, OnFrameRequestQueueChanged)); + + /// + private static void OnFrameRequestQueueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @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(); + } + } + + /// + /// Gets or sets the instance to use to render content. + /// + public IShaderRunner? ShaderRunner + { + get => (IShaderRunner?)GetValue(ShaderRunnerProperty); + set => SetValue(ShaderRunnerProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty ShaderRunnerProperty = DependencyProperty.Register( nameof(ShaderRunner), typeof(IShaderRunner), typeof(ComputeShaderPanel), - new PropertyMetadata(null, static (d, e) => ((ComputeShaderPanel)d).shaderRunner = (IShaderRunner?)e.NewValue)); + new PropertyMetadata(null, OnShaderRunnerPropertyChanged)); + + /// + private static void OnShaderRunnerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @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(); + } + } /// /// Gets or sets the resolution scale to be used to render frames. @@ -56,12 +138,7 @@ public sealed unsafe partial class ComputeShaderPanel var @this = (ComputeShaderPanel)d; var resolutionScale = (double)e.NewValue; - @this.targetResolutionScale = (float)resolutionScale; - - if (!@this.isDynamicResolutionEnabled) - { - @this.OnResize(); - } + @this.swapChainManager.QueueResolutionScaleChange(resolutionScale); } /// @@ -90,40 +167,6 @@ public sealed unsafe partial class ComputeShaderPanel var @this = (ComputeShaderPanel)d; var isDynamicResolutionEnabled = (bool)e.NewValue; - @this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; - } - - /// - /// Gets or sets whether or not the rendering is paused. - /// - public bool IsPaused - { - get => (bool)GetValue(IsPausedProperty); - set => SetValue(IsPausedProperty, value); - } - - /// - /// The backing . - /// - public static readonly DependencyProperty IsPausedProperty = DependencyProperty.Register( - nameof(IsPaused), - typeof(bool), - typeof(ComputeShaderPanel), - new PropertyMetadata(false, OnIsPausedPropertyChanged)); - - /// - private static void OnIsPausedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - var @this = (ComputeShaderPanel)d; - var isPaused = (bool)e.NewValue; - - if (isPaused) - { - @this.OnStopRenderLoop(); - } - else - { - @this.OnStartRenderLoop(); - } + @this.swapChainManager.QueueDynamicResolutionModeChange(isDynamicResolutionEnabled); } } diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 70d86b9d..8750e3dc 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -1,76 +1,78 @@ #if WINDOWS_UWP +using ComputeSharp.Uwp.Helpers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; - -namespace ComputeSharp.Uwp; #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 /// +/// /// A custom that can be used to render animated backgrounds. /// It is powered by ComputeSharp and leverages compute shaders to create frames to display. +/// +/// +/// This panel accepts a custom instance to customize frame requests. +/// /// -public sealed unsafe partial class ComputeShaderPanel : SwapChainPanel +public sealed partial class ComputeShaderPanel : SwapChainPanel { + /// + /// The instance handling rendering. + /// + private readonly SwapChainManager swapChainManager; + /// /// Creates a new instance. /// - public ComputeShaderPanel() + public unsafe ComputeShaderPanel() { + this.swapChainManager = new SwapChainManager(this); + this.Loaded += ComputeShaderPanel_Loaded; this.Unloaded += ComputeShaderPanel_Unloaded; this.SizeChanged += ComputeShaderPanel_SizeChanged; this.CompositionScaleChanged += ComputeShaderPanel_CompositionScaleChanged; } - /// - /// Finalizes the current instance and releases all resources. - /// - ~ComputeShaderPanel() - { - OnDisposed(); - } - // Initializes the swap chain and starts the render thread private void ComputeShaderPanel_Loaded(object sender, RoutedEventArgs e) { - this.width = (float)ActualWidth; - this.height = (float)ActualHeight; - this.compositionScaleX = CompositionScaleX; - this.compositionScaleY = CompositionScaleY; - this.resolutionScale = (float)ResolutionScale; - this.targetResolutionScale = 1.0f; - this.isDynamicResolutionEnabled = true; + this.swapChainManager.QueueResize(ActualWidth, ActualHeight); + this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); + this.swapChainManager.QueueResolutionScaleChange(ResolutionScale); + this.swapChainManager.QueueDynamicResolutionModeChange(IsDynamicResolutionEnabled); - OnInitialize(); - OnStartRenderLoop(); + 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) { - OnStopRenderLoop(); + 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.width = (float)e.NewSize.Width; - this.height = (float)e.NewSize.Height; - - OnResize(); + 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.compositionScaleX = CompositionScaleX; - this.compositionScaleY = CompositionScaleY; - - OnResize(); + this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); } } diff --git a/src/ComputeSharp.UI/Extensions/SemaphoreSlimExtensions.cs b/src/ComputeSharp.UI/Extensions/SemaphoreSlimExtensions.cs new file mode 100644 index 00000000..fd2ab3d0 --- /dev/null +++ b/src/ComputeSharp.UI/Extensions/SemaphoreSlimExtensions.cs @@ -0,0 +1,56 @@ +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 + +/// +/// A helper type for . +/// +internal static class SemaphoreSlimExtensions +{ + /// + /// Acquires a lock for the current instance, that is automatically released outside the block. + /// + public static async ValueTask LockAsync(this SemaphoreSlim semaphore) + { + await semaphore.WaitAsync().ConfigureAwait(false); + + return new(semaphore); + } + + /// + /// Private class that implements the automatic release of the semaphore + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public readonly struct Lock : IDisposable + { + /// + /// The underlying semaphore used by this instance. + /// + private readonly SemaphoreSlim semaphore; + + /// + /// Creates a new instance. + /// + /// The instance to wrap. + [Obsolete("Use AsyncMutex.LockAsync instead.")] + public Lock(SemaphoreSlim semaphore) + { + this.semaphore = semaphore; + } + + /// + public void Dispose() + { + this.semaphore.Release(); + } + } +} diff --git a/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs b/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs index 26b9004e..cfbbc869 100644 --- a/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs +++ b/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs @@ -118,10 +118,9 @@ internal unsafe ref struct DynamicResolutionManager if (averageFrameTimeInTicks is < LowerFrameTimeThresholdInTicksFor60fps or > UpperFrameTimeThresholdInTicksFor60fps) { - float - frameTimeDelta = (TargetFrameTimeInTicksFor60fps - averageFrameTimeInTicks) / (float)averageFrameTimeInTicks, - scaleFactorDelta = scaleFactor * frameTimeDelta * ScaleFactorDeltaK, - updatedScaleFactor = Math.Clamp(scaleFactor + scaleFactorDelta, 0.10f, 1.0f); + float frameTimeDelta = (TargetFrameTimeInTicksFor60fps - 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. diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs new file mode 100644 index 00000000..ef540584 --- /dev/null +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -0,0 +1,360 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading; +#if WINDOWS_UWP +using ComputeSharp.Uwp.Extensions; +#else +using ComputeSharp.WinUI.Extensions; +#endif +using Microsoft.Toolkit.Diagnostics; + +#pragma warning disable CS0420 + +#if WINDOWS_UWP +namespace ComputeSharp.Uwp.Helpers; +#else +namespace ComputeSharp.WinUI.Helpers; +#endif + +/// +partial class SwapChainManager +{ + /// + /// Starts the current render loop. + /// + /// The instance to use, if available. + /// The instance to use to render frames. + public async void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner) + { + ThrowIfDisposed(); + + Guard.IsNotNull(shaderRunner, nameof(shaderRunner)); + + using (await this.setupSemaphore.LockAsync()) + { + this.renderCancellationTokenSource?.Cancel(); + + await this.renderSemaphore.WaitAsync(); + + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + + this.frameRequestQueue = frameRequestQueue; + this.shaderRunner = shaderRunner; + this.renderCancellationTokenSource = new CancellationTokenSource(); + this.renderThread = newRenderThread; + this.renderSemaphore = new SemaphoreSlim(0, 1); + + newRenderThread.Start(this); + } + } + + /// + /// Stops the current render loop, if one is running. + /// + public async void StopRenderLoop() + { + ThrowIfDisposed(); + + using (await this.setupSemaphore.LockAsync()) + { + this.renderCancellationTokenSource?.Cancel(); + } + } + + /// + /// Queues a change in the dynamic resolution mode. + /// + /// Whether or not to use dynamic resolution. + public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) + { + ThrowIfDisposed(); + + using (await this.setupSemaphore.LockAsync()) + { + // If there is a render thread currently running, stop it and restart it + if (this.renderCancellationTokenSource?.IsCancellationRequested == false) + { + this.renderCancellationTokenSource?.Cancel(); + + await this.renderSemaphore.WaitAsync(); + + Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); + + this.renderCancellationTokenSource = new CancellationTokenSource(); + this.renderThread = newRenderThread; + this.renderSemaphore = new SemaphoreSlim(0, 1); + this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; + + newRenderThread.Start(this); + } + else + { + this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; + } + } + } + + /// + /// Queues a resize operation. + /// + /// The width of the render resolution. + /// The height of the render resolution. + public void QueueResize(double width, double height) + { + ThrowIfDisposed(); + + this.width = (float)width; + this.height = (float)height; + + this.isResizePending = true; + } + + /// + /// Queues a change in the composition scale factors. + /// + /// The composition scale on the X axis. + /// The composition scale on the Y axis + public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) + { + ThrowIfDisposed(); + + this.compositionScaleX = (float)compositionScaleX; + this.compositionScaleY = (float)compositionScaleY; + + this.isResizePending = true; + } + + /// + /// Queues a change in the resolution scale factor. + /// + /// The resolution scale factor to use. + public void QueueResolutionScaleChange(double resolutionScale) + { + ThrowIfDisposed(); + + this.resolutionScale = (float)resolutionScale; + + this.isResizePending = true; + } + + /// + /// Selects the right render loop to start. + /// + private void SwitchAndStartRenderLoop() + { + try + { + OnRenderingStarted(); + + if (this.isDynamicResolutionEnabled) + { + this.targetResolutionScale = 1.0f; + + RenderLoopWithDynamicResolution(); + } + else + { + this.targetResolutionScale = this.resolutionScale; + + RenderLoop(); + } + + OnRenderingStopped(); + } + catch (Exception e) + { + OnRenderingFailed(e); + } + finally + { + this.renderSemaphore.Release(); + } + } + + /// + /// The core render loop. + /// + private void RenderLoop() + { + Stopwatch renderStopwatch = this.renderStopwatch ??= new(); + CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; + + if (!OnFrameRequest(out object? parameter, cancellationToken)) + { + return; + } + + // 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. + OnResize(); + OnUpdate(renderStopwatch.Elapsed, parameter); + OnPresent(); + + renderStopwatch.Start(); + + // Main render loop, until cancellation is requested + while (!cancellationToken.IsCancellationRequested) + { + if (!OnFrameRequest(out parameter, cancellationToken)) + { + return; + } + + OnResize(); + OnUpdate(renderStopwatch.Elapsed, parameter); + OnPresent(); + } + + renderStopwatch.Stop(); + } + + /// + /// The core render loop with dynamic resolution. + /// + private void RenderLoopWithDynamicResolution() + { + Stopwatch renderStopwatch = this.renderStopwatch ??= new(); + CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; + + DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + + if (!OnFrameRequest(out object? parameter, cancellationToken)) + { + return; + } + + Stopwatch frameStopwatch = Stopwatch.StartNew(); + + OnResize(); + OnUpdate(renderStopwatch.Elapsed, parameter); + OnPresent(); + + renderStopwatch.Start(); + + while (!cancellationToken.IsCancellationRequested) + { + // Evaluate the dynamic resolution frame time step, if the mode is enabled + if (frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref this.targetResolutionScale)) + { + this.isResizePending = true; + } + + if (!OnFrameRequest(out parameter, cancellationToken)) + { + return; + } + + frameStopwatch.Restart(); + + OnResize(); + OnUpdate(renderStopwatch.Elapsed, parameter); + OnPresent(); + } + + renderStopwatch.Stop(); + } + + /// + /// Waits for a new frame request and retrieves its parameter. + /// + /// The input parameter for the frame to render. + /// A token to cancel waiting for a new frame. + /// Whether the operation was canceled. + 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; + } + + /// + /// Resizes the current application, if needed. + /// + private void OnResize() + { + if (this.isResizePending) + { + ApplyResize(); + + this.isResizePending = false; + } + } + + /// + /// Updates the render resolution, if needed, and renders a new frame. + /// + /// The current time since the start of the application. + /// The input parameter for the frame being rendered. + private void OnUpdate(TimeSpan time, object? parameter) + { + this.shaderRunner!.Execute(this.texture!, time, parameter); + } + + /// + /// Presents the last rendered frame for the current application. + /// + private unsafe partial void OnPresent(); + + /// + /// Raises . + /// + private void OnRenderingStarted() + { + _ = this.dispatcherQueue.TryEnqueue(() => RenderingStarted?.Invoke(this.owner, EventArgs.Empty)); + } + + /// + /// Raises . + /// + private void OnRenderingStopped() + { + _ = this.dispatcherQueue.TryEnqueue(() => RenderingStopped?.Invoke(this.owner, EventArgs.Empty)); + } + + /// + /// Raises . + /// + /// The being thrown that caused rendering to stop. + private void OnRenderingFailed(Exception e) + { + _ = this.dispatcherQueue.TryEnqueue(() => RenderingFailed?.Invoke(this.owner, e)); + } + + /// + /// Stops the current render loop, if one is running, and waits for it. + /// + /// This method doesn't check for disposal. + private void UnsafeStopRenderLoopAndWait() + { + ThrowIfDisposed(); + + this.setupSemaphore.Wait(); + + this.renderCancellationTokenSource?.Cancel(); + this.renderSemaphore.Wait(); + } +} diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs similarity index 71% rename from src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs rename to src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 855c3223..babdc16c 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -1,45 +1,54 @@ using System; using System.Diagnostics; -#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.Helpers; -#else -using ComputeSharp.WinUI.Helpers; +#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 +#if WINDOWS_UWP +using System.Runtime.InteropServices; +using Windows.Foundation; +using Windows.UI.Xaml.Controls; +using Windows.System; +#else +using Windows.Foundation; using WinRT; #endif using Win32 = TerraFX.Interop.Windows.Windows; -#pragma warning disable CS0420 - #if WINDOWS_UWP -namespace ComputeSharp.Uwp; +namespace ComputeSharp.Uwp.Helpers; #else -namespace ComputeSharp.WinUI; +namespace ComputeSharp.WinUI.Helpers; #endif -/// -public sealed partial class ComputeShaderPanel +/// +/// A type managing rendering on a target swap chain object. +/// +/// The type of the owner instance. +internal sealed unsafe partial class SwapChainManager : NativeObject + where TOwner : SwapChainPanel { /// - /// The render thread in use, if any. + /// The owning instance. /// - private Thread? renderThread; + private readonly TOwner owner; /// - /// The instance used to create shaders to run. + /// The captured for the current instance. /// - private IShaderRunner? shaderRunner; + private readonly DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread(); + + /// + /// An object for the render loop management. + /// + private readonly SemaphoreSlim setupSemaphore = new(1, 1); /// /// The pointer for the device currently in use. @@ -59,7 +68,7 @@ public sealed partial class ComputeShaderPanel /// /// The next fence value for graphics operations using . /// - private ulong nextD3D12FenceValue = 1; + private ulong nextD3D12FenceValue; /// /// The object to create command lists. @@ -94,12 +103,37 @@ public sealed partial class ComputeShaderPanel /// /// The index of the next buffer that can be used to present content. /// - private uint currentBufferIndex; + private volatile uint currentBufferIndex; + + /// + /// The render thread in use, if any. + /// + private volatile Thread? renderThread; + + /// + /// The used to wait for render threads to complete. + /// + private volatile SemaphoreSlim renderSemaphore = new(1, 1); + + /// + /// The to use for . + /// + private volatile CancellationTokenSource? renderCancellationTokenSource; + + /// + /// The instance used to get frame requests and parameters. + /// + private volatile IFrameRequestQueue? frameRequestQueue; + + /// + /// The instance used to create shaders to run. + /// + private volatile IShaderRunner? shaderRunner; /// /// The instance used to prepare frames to display. /// - private ReadWriteTexture2D? texture; + private volatile ReadWriteTexture2D? texture; /// /// Whether or not the window has been resized and requires the buffers to be updated. @@ -141,37 +175,57 @@ public sealed partial class ComputeShaderPanel /// private volatile bool isDynamicResolutionEnabled; - /// - /// Indicates whether or not the rendering has been canceled. - /// - private volatile bool isCancellationRequested; - /// /// The instance tracking time since the first rendered frame. /// - private Stopwatch? renderStopwatch; + private volatile Stopwatch? renderStopwatch; /// - /// Indicates whether or not has already been called. + /// Raised whenever rendering starts. /// - private bool isInitialized; + public event TypedEventHandler? RenderingStarted; /// - /// Initializes the current application. + /// Raised whenever rendering stops. /// - private unsafe void OnInitialize() + public event TypedEventHandler? RenderingStopped; + + /// + /// Raised whenever rendering fails. + /// + public event TypedEventHandler? RenderingFailed; + + /// + /// Initializes a new instance of the type. + /// + /// The input swap chain instance being used. + public SwapChainManager(TOwner owner) { - if (this.isInitialized) - { - return; - } + this.owner = owner; - this.isInitialized = true; + // 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. + using ComPtr swapChainPanelNative = default; + +#if WINDOWS_UWP + IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(owner); + + swapChainPanel->QueryInterface( + Win32.__uuidof(), + (void**)&swapChainPanelNative).Assert(); +#else + IUnknown* swapChainPanel = (IUnknown*)((IWinRTObject)owner).NativeObject.ThisPtr; + Guid iSwapChainPanelNativeUuid = new(0x63AAD0B8, 0x7C24, 0x40FF, 0x85, 0xA8, 0x64, 0x0D, 0x94, 0x4C, 0xC3, 0x25); + + swapChainPanel->QueryInterface( + &iSwapChainPanelNativeUuid, + (void**)&swapChainPanelNative).Assert(); +#endif // Get the underlying ID3D12Device in use fixed (ID3D12Device** d3D12Device = this.d3D12Device) { - InteropServices.TryGetID3D12Device(GraphicsDevice.Default, Win32.__uuidof(), (void**)d3D12Device).Assert(); + GraphicsDevice.Default.D3D12Device->QueryInterface(Win32.__uuidof(), (void**)d3D12Device).Assert(); } // Create the direct command queue to use @@ -258,25 +312,6 @@ public sealed partial class ComputeShaderPanel // Close the command list to prepare it for future use this.d3D12GraphicsCommandList.Get()->Close().Assert(); - // 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. - using ComPtr swapChainPanelNative = default; - -#if WINDOWS_UWP - IUnknown* swapChainPanel = (IUnknown*)Marshal.GetIUnknownForObject(this); - - swapChainPanel->QueryInterface( - Win32.__uuidof(), - (void**)&swapChainPanelNative).Assert(); -#else - IUnknown* swapChainPanel = (IUnknown*)((IWinRTObject)this).NativeObject.ThisPtr; - Guid iSwapChainPanelNativeUuid = new(0x63AAD0B8, 0x7C24, 0x40FF, 0x85, 0xA8, 0x64, 0x0D, 0x94, 0x4C, 0xC3, 0x25); - - swapChainPanel->QueryInterface( - &iSwapChainPanelNativeUuid, - (void**)&swapChainPanelNative).Assert(); -#endif - using (ComPtr idxgiSwapChain = default) { this.dxgiSwapChain3.CopyTo(&idxgiSwapChain).Assert(); @@ -287,25 +322,17 @@ public sealed partial class ComputeShaderPanel GC.KeepAlive(this); } - /// - /// Resizes the current application. - /// - private void OnResize() - { - this.isResizePending = true; - } - /// /// Applies the actual resize logic that was scheduled from . /// private unsafe void ApplyResize() { - this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue).Assert(); + 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(this.nextD3D12FenceValue, default).Assert(); - - this.nextD3D12FenceValue++; + this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert(); // Dispose the old buffers before resizing the buffer this.d3D12Resource0.Dispose(); @@ -347,40 +374,16 @@ public sealed partial class ComputeShaderPanel (int)d3D12Resource0Description.Height); } - /// - /// Updates the render resolution, if needed, and renders a new frame. - /// - /// The current time since the start of the application. - private unsafe void OnUpdate(TimeSpan time) + /// + private unsafe partial void OnPresent() { - if (this.isResizePending) - { - ApplyResize(); - - this.isResizePending = false; - } - - // Skip if no factory is available - if (this.shaderRunner is null) - { - return; - } - - // Generate the new frame - this.shaderRunner.Execute(this.texture!, time); - } - - /// - /// Presents the last rendered frame for the current application. - /// - private unsafe void OnPresent() - { - _ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, 1); + // Wait for the swap chain to be ready for presenting + _ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, true); using ComPtr d3D12Resource = default; // Get the underlying ID3D12Resource pointer for the texture - InteropServices.TryGetID3D12Resource(this.texture!, Win32.__uuidof(), (void**)d3D12Resource.GetAddressOf()).Assert(); + this.texture!.D3D12Resource->QueryInterface(Win32.__uuidof(), (void**)d3D12Resource.GetAddressOf()).Assert(); // Get the target back buffer to update ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch @@ -431,116 +434,40 @@ public sealed partial class ComputeShaderPanel // Execute the command list to perform the copy this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)this.d3D12GraphicsCommandList.GetAddressOf()); - this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue).Assert(); + + // 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(0, 0).Assert(); - if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) + if (updatedFenceValue > this.d3D12Fence.Get()->GetCompletedValue()) { - this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default).Assert(); + this.d3D12Fence.Get()->SetEventOnCompletion(updatedFenceValue, default).Assert(); } - - this.nextD3D12FenceValue++; } - /// - /// Executes the render loop for the current panel. - /// - /// This method assumes to be invoked from a background thread. - private void OnStartRenderLoop() + /// + protected override void OnDispose() { - static void ExecuteRenderLoop(ComputeShaderPanel @this) + ThreadPool.UnsafeQueueUserWorkItem(static state => { - Stopwatch - renderStopwatch = @this.renderStopwatch ??= new(), - frameStopwatch = Stopwatch.StartNew(); + SwapChainManager @this = (SwapChainManager)state!; - DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + @this.UnsafeStopRenderLoopAndWait(); - bool isDynamicResolutionEnabled = @this.isDynamicResolutionEnabled; - - // 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. - @this.OnUpdate(renderStopwatch.Elapsed); - @this.OnPresent(); - - renderStopwatch.Start(); - - const long targetFrameTimeInTicksFor61fps = 163934; - - // Main render loop, until cancellation is requested - while (!@this.isCancellationRequested) - { - // Update the resolution mode, if needed - if (isDynamicResolutionEnabled != @this.isDynamicResolutionEnabled) - { - isDynamicResolutionEnabled = !isDynamicResolutionEnabled; - - if (isDynamicResolutionEnabled) - { - DynamicResolutionManager.Create(out frameTimeWatcher); - } - else - { - @this.targetResolutionScale = @this.resolutionScale; - } - } - - // Evaluate the dynamic resolution frame time step, if the mode is enabled - if (isDynamicResolutionEnabled && - frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref @this.targetResolutionScale)) - { - @this.isResizePending = true; - } - - while (frameStopwatch.ElapsedTicks < targetFrameTimeInTicksFor61fps) - { - } - - frameStopwatch.Restart(); - - @this.OnUpdate(renderStopwatch.Elapsed); - @this.OnPresent(); - } - - renderStopwatch.Stop(); - } - - this.isCancellationRequested = false; - this.renderThread = new Thread(static args => ExecuteRenderLoop((ComputeShaderPanel)args!)); - this.renderThread.Start(this); - } - - /// - /// Stops the current render loop, if one is running. - /// - private void OnStopRenderLoop() - { - this.isCancellationRequested = true; - } - - /// - /// Stops the current render loop, and releases all resources. - /// - private void OnDisposed() - { - this.isCancellationRequested = true; - - // Ensure the rendering has stopped - if (this.renderThread is Thread renderThread) - { - renderThread.Join(); - } - - 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.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); } } diff --git a/src/ComputeSharp.UI/IFrameRequestQueue.cs b/src/ComputeSharp.UI/IFrameRequestQueue.cs new file mode 100644 index 00000000..41a1e719 --- /dev/null +++ b/src/ComputeSharp.UI/IFrameRequestQueue.cs @@ -0,0 +1,20 @@ +using System.Threading; + +#if WINDOWS_UWP +namespace ComputeSharp.Uwp; +#else +namespace ComputeSharp.WinUI; +#endif + +/// +/// An interface for a shader runner to be used with . +/// +public interface IFrameRequestQueue +{ + /// + /// Waits for a new frame request to be available, retrieving its parameter, if any. + /// + /// The input parameter for the frame to render. + /// A token to cancel waiting for a new frame. + void Dequeue(out object? parameter, CancellationToken token); +} diff --git a/src/ComputeSharp.UI/IShaderRunner.cs b/src/ComputeSharp.UI/IShaderRunner.cs index c681b68b..a3c5aca3 100644 --- a/src/ComputeSharp.UI/IShaderRunner.cs +++ b/src/ComputeSharp.UI/IShaderRunner.cs @@ -16,5 +16,6 @@ public interface IShaderRunner /// /// The target texture to render the frame to. /// The timespan for the current frame. - public void Execute(IReadWriteTexture2D texture, TimeSpan timespan); + /// The input parameter for the frame being rendered. + void Execute(IReadWriteTexture2D texture, TimeSpan timespan, object? parameter); } diff --git a/src/ComputeSharp.UI/ShaderRunner{T}.cs b/src/ComputeSharp.UI/ShaderRunner{T}.cs index 370089d6..e1d43722 100644 --- a/src/ComputeSharp.UI/ShaderRunner{T}.cs +++ b/src/ComputeSharp.UI/ShaderRunner{T}.cs @@ -1,4 +1,5 @@ using System; +using Microsoft.Toolkit.Diagnostics; #if WINDOWS_UWP namespace ComputeSharp.Uwp; @@ -14,9 +15,14 @@ public sealed class ShaderRunner : IShaderRunner where T : struct, IPixelShader { /// - /// The instance used to create shaders to run. + /// The instance used to create shaders to run. /// - private readonly Func shaderFactory; + private readonly Func? shaderFactory; + + /// + /// The instance used to create shaders to run. + /// + private readonly Func? statefulShaderFactory; /// /// Creates a new instance that will create shader instances with @@ -25,21 +31,40 @@ public sealed class ShaderRunner : IShaderRunner /// public ShaderRunner() { - this.shaderFactory = static _ => default; } /// /// Creates a new instance. /// - /// The instance used to create shaders to run. + /// The instance used to create shaders to run. public ShaderRunner(Func shaderFactory) { + Guard.IsNotNull(shaderFactory, nameof(shaderFactory)); + this.shaderFactory = shaderFactory; } - /// - public void Execute(IReadWriteTexture2D texture, TimeSpan time) + /// + /// Creates a new instance. + /// + /// The instance used to create shaders to run. + public ShaderRunner(Func shaderFactory) { - GraphicsDevice.Default.ForEach(texture, this.shaderFactory(time)); + Guard.IsNotNull(shaderFactory, nameof(shaderFactory)); + + this.statefulShaderFactory = shaderFactory; + } + + /// + public void Execute(IReadWriteTexture2D texture, TimeSpan time, object? parameter) + { + if (this.shaderFactory is Func shaderFactory) + { + GraphicsDevice.Default.ForEach(texture, this.shaderFactory(time)); + } + else + { + GraphicsDevice.Default.ForEach(texture, this.statefulShaderFactory!(time, parameter)); + } } }