diff --git a/samples/ComputeSharp.SwapChain.Core.Shared/Constants/Event.cs b/samples/ComputeSharp.SwapChain.Core.Shared/Constants/Event.cs index 35cec680..9d2fe8ad 100644 --- a/samples/ComputeSharp.SwapChain.Core.Shared/Constants/Event.cs +++ b/samples/ComputeSharp.SwapChain.Core.Shared/Constants/Event.cs @@ -5,6 +5,7 @@ /// public static class Event { + public const string IsVerticalSyncEnabledChanged = "[SETTINGS] IsVerticalSyncEnabled"; public const string IsDynamicResolutionEnabledChanged = "[SETTINGS] IsDynamicResolutionEnabled"; public const string SelectedResolutionScaleChanged = "[SETTINGS] SelectedResolutionScale"; public const string SelectedComputeShaderChanged = "[SETTINGS] SelectedComputeShader"; diff --git a/samples/ComputeSharp.SwapChain.Core.Shared/ViewModels/MainViewModel.cs b/samples/ComputeSharp.SwapChain.Core.Shared/ViewModels/MainViewModel.cs index 259a499f..b97858db 100644 --- a/samples/ComputeSharp.SwapChain.Core.Shared/ViewModels/MainViewModel.cs +++ b/samples/ComputeSharp.SwapChain.Core.Shared/ViewModels/MainViewModel.cs @@ -35,6 +35,7 @@ public sealed class MainViewModel : ObservableObject Guard.IsNotNull(analyticsService, nameof(analyticsService)); this.analyticsService = analyticsService; + this.isVerticalSyncEnabled = true; this.isDynamicResolutionEnabled = true; this.selectedResolutionScale = 100; this.selectedComputeShader = ComputeShaderOptions[0]; @@ -49,6 +50,23 @@ public sealed class MainViewModel : ObservableObject /// public IList ResolutionScaleOptions { get; } = new[] { 25, 50, 75, 100 }; + private bool isVerticalSyncEnabled; + + /// + /// Gets or sets whether the vertical sync is enabled. + /// + public bool IsVerticalSyncEnabled + { + get => this.isVerticalSyncEnabled; + set + { + if (SetProperty(ref this.isVerticalSyncEnabled, value)) + { + this.analyticsService.Log(Event.IsVerticalSyncEnabledChanged, (nameof(value), value)); + } + } + } + private bool isDynamicResolutionEnabled; /// diff --git a/samples/ComputeSharp.SwapChain.Uwp/App.xaml b/samples/ComputeSharp.SwapChain.Uwp/App.xaml index c01ce6cb..1afbd8c5 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/App.xaml +++ b/samples/ComputeSharp.SwapChain.Uwp/App.xaml @@ -1,4 +1,8 @@  + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> + + + + diff --git a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj index 697e6c87..f854920d 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj +++ b/samples/ComputeSharp.SwapChain.Uwp/ComputeSharp.SwapChain.Uwp.csproj @@ -208,10 +208,10 @@ 7.1.2 - 4.4.0 + 4.5.0 - 4.4.0 + 4.5.0 6.0.0 @@ -225,6 +225,9 @@ 7.1.2 + + 2.7.0 + diff --git a/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml b/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml index f453cc71..a751b6ec 100644 --- a/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml +++ b/samples/ComputeSharp.SwapChain.Uwp/Views/MainView.xaml @@ -154,6 +154,7 @@ Grid.Row="1" IsDynamicResolutionEnabled="{x:Bind ViewModel.IsDynamicResolutionEnabled, Mode=OneWay}" IsPaused="{x:Bind ViewModel.IsRenderingPaused, Mode=OneWay}" + IsVerticalSyncEnabled="{x:Bind ViewModel.IsVerticalSyncEnabled, Mode=OneWay}" RenderingFailed="MainShaderPanel_RenderingFailed" ResolutionScale="{x:Bind converters:ResolutionScaleConverter.ConvertPercentageToScale(ViewModel.SelectedResolutionScale), Mode=OneWay}" ShaderRunner="{x:Bind ViewModel.SelectedComputeShader.ShaderRunner, Mode=OneWay}" /> @@ -192,6 +193,7 @@ + + /// Gets or sets whether vertical sync is enabled. + /// The default value for this property is . + /// + public bool IsVerticalSyncEnabled + { + get => (bool)GetValue(IsVerticalSyncEnabledProperty); + set => SetValue(IsVerticalSyncEnabledProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty IsVerticalSyncEnabledProperty = DependencyProperty.Register( + nameof(IsVerticalSyncEnabled), + typeof(bool), + typeof(AnimatedComputeShaderPanel), + new PropertyMetadata(true, OnIsVerticalSyncEnabledPropertyChanged)); + + /// + private static void OnIsVerticalSyncEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (AnimatedComputeShaderPanel)d; + var isVerticalSyncEnabled = (bool)e.NewValue; + + @this.swapChainManager.QueueVerticalSyncModeChange(isVerticalSyncEnabled); + } + /// /// Gets or sets whether or not the rendering is paused. /// diff --git a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs index 27b77bc1..7fb592ae 100644 --- a/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/AnimatedComputeShaderPanel.cs @@ -50,6 +50,7 @@ public sealed partial class AnimatedComputeShaderPanel : SwapChainPanel this.swapChainManager.QueueCompositionScaleChange(CompositionScaleX, CompositionScaleY); this.swapChainManager.QueueResolutionScaleChange(ResolutionScale); this.swapChainManager.QueueDynamicResolutionModeChange(IsDynamicResolutionEnabled); + this.swapChainManager.QueueVerticalSyncModeChange(IsVerticalSyncEnabled); if (!IsPaused && ShaderRunner is IShaderRunner shaderRunner) diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs index 7e351bc0..7c76dc3c 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.Properties.cs @@ -169,4 +169,32 @@ partial class ComputeShaderPanel @this.swapChainManager.QueueDynamicResolutionModeChange(isDynamicResolutionEnabled); } + + /// + /// Gets or sets whether vertical sync is enabled. + /// The default value for this property is . + /// + public bool IsVerticalSyncEnabled + { + get => (bool)GetValue(IsVerticalSyncEnabledProperty); + set => SetValue(IsVerticalSyncEnabledProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty IsVerticalSyncEnabledProperty = DependencyProperty.Register( + nameof(IsVerticalSyncEnabled), + typeof(bool), + typeof(ComputeShaderPanel), + new PropertyMetadata(true, OnIsVerticalSyncEnabledPropertyChanged)); + + /// + private static void OnIsVerticalSyncEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (ComputeShaderPanel)d; + var isVerticalSyncEnabled = (bool)e.NewValue; + + @this.swapChainManager.QueueVerticalSyncModeChange(isVerticalSyncEnabled); + } } diff --git a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs index 8750e3dc..560f1950 100644 --- a/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.UI/Controls/ComputeShaderPanel.cs @@ -50,6 +50,7 @@ public sealed partial class ComputeShaderPanel : SwapChainPanel 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) diff --git a/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs b/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs index cfbbc869..ac3b07ec 100644 --- a/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs +++ b/src/ComputeSharp.UI/Helpers/DynamicResolutionManager.cs @@ -1,7 +1,5 @@ using System; -#if !WINDOWS_UWP -using System.Runtime.InteropServices; -#endif +using System.Runtime.CompilerServices; using System.Threading; #if WINDOWS_UWP @@ -15,21 +13,6 @@ namespace ComputeSharp.WinUI.Helpers; /// internal unsafe ref struct DynamicResolutionManager { - /// - /// The target frame time in ticks to reach 60fps (set to 64fps). - /// - public const long TargetFrameTimeInTicksFor60fps = 156250; - - /// - /// The upper frame time threshold in ticks to reach 60fps. - /// - private const long UpperFrameTimeThresholdInTicksFor60fps = 166666; - - /// - /// The lower frame time threshold in ticks to reach 60fps (set to 68fps). - /// - private const long LowerFrameTimeThresholdInTicksFor60fps = 147058; - /// /// The size of the sliding frame time window to monitor frame times. /// @@ -45,6 +28,21 @@ internal unsafe ref struct DynamicResolutionManager /// private const float ScaleFactorDeltaK = 0.8f; + /// + /// The target frame time in ticks. + /// + private readonly long targetFrameTimeInTicks; + + /// + /// The upper frame time threshold in ticks. + /// + private readonly long upperFrameTimeThresholdInTicks; + + /// + /// The lower frame time threshold in ticks. + /// + private readonly long lowerFrameTimeThresholdInTicks; + /// /// The window of registered frame times for previous frames. /// @@ -68,20 +66,20 @@ internal unsafe ref struct DynamicResolutionManager /// /// Initializes a new instance. /// - /// The resulting instance. - public static void Create(out DynamicResolutionManager manager) + /// The target framerate to use. + public DynamicResolutionManager(int targetFramerate) { - manager.frameTimeOffset = 0; - manager.slidingFrameTimeWindowSum = TargetFrameTimeInTicksFor60fps * SlidingFrameTimeWindowLength; + long targetFrameTimeInTicks = TimeSpan.FromSeconds(1).Ticks / targetFramerate; + long upperFrameTimeThresholdInTicks = TimeSpan.FromSeconds(1).Ticks / (targetFramerate - 2); + long lowerFrameTimeThresholdInTicks = TimeSpan.FromSeconds(1).Ticks / (targetFramerate + 2); -#if WINDOWS_UWP - fixed (long* p = &manager.frameTimesInTicks[0]) - { - new Span(p, SlidingFrameTimeWindowLength).Fill(TargetFrameTimeInTicksFor60fps); - } -#else - MemoryMarshal.CreateSpan(ref manager.frameTimesInTicks[0], SlidingFrameTimeWindowLength).Fill(TargetFrameTimeInTicksFor60fps); -#endif + this.frameTimeOffset = 0; + this.targetFrameTimeInTicks = targetFrameTimeInTicks; + this.upperFrameTimeThresholdInTicks = upperFrameTimeThresholdInTicks; + this.lowerFrameTimeThresholdInTicks = lowerFrameTimeThresholdInTicks; + this.slidingFrameTimeWindowSum = targetFrameTimeInTicks * SlidingFrameTimeWindowLength; + + new Span(Unsafe.AsPointer(ref this.frameTimesInTicks[0]), SlidingFrameTimeWindowLength).Fill(targetFrameTimeInTicks); } /// @@ -116,9 +114,10 @@ internal unsafe ref struct DynamicResolutionManager // 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 is < LowerFrameTimeThresholdInTicksFor60fps or > UpperFrameTimeThresholdInTicksFor60fps) + if (averageFrameTimeInTicks < lowerFrameTimeThresholdInTicks || + averageFrameTimeInTicks > upperFrameTimeThresholdInTicks) { - float frameTimeDelta = (TargetFrameTimeInTicksFor60fps - averageFrameTimeInTicks) / (float)averageFrameTimeInTicks; + float frameTimeDelta = (targetFrameTimeInTicks - averageFrameTimeInTicks) / (float)averageFrameTimeInTicks; float scaleFactorDelta = scaleFactor * frameTimeDelta * ScaleFactorDeltaK; float updatedScaleFactor = Math.Clamp(scaleFactor + scaleFactorDelta, 0.10f, 1.0f); diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs index e99c28d4..9a51483a 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.Rendering.cs @@ -97,6 +97,40 @@ partial class SwapChainManager } } + /// + /// Queues a change in the vertical sync mode. + /// + /// Whether or not to use vertical sync. + public async void QueueVerticalSyncModeChange(bool isVerticalSyncEnabled) + { + ThrowIfDisposed(); + + 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) + { + 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.syncInterval = isVerticalSyncEnabled ? 1u : 0u; + + newRenderThread.Start(this); + } + else + { + this.syncInterval = isVerticalSyncEnabled ? 1u : 0u; + } + } + } + /// /// Queues a resize operation. /// @@ -160,10 +194,14 @@ partial class SwapChainManager RenderLoop(); } + this.renderStopwatch?.Stop(); + OnRenderingStopped(); } catch (Exception e) { + this.renderStopwatch?.Stop(); + OnRenderingFailed(e); } finally @@ -192,6 +230,7 @@ partial class SwapChainManager // resuming after a pause correctly renders the first frame at the right time. if (OnUpdate(renderStopwatch.Elapsed, parameter)) { + OnWaitForPresent(); OnPresent(); } @@ -209,11 +248,10 @@ partial class SwapChainManager if (OnUpdate(renderStopwatch.Elapsed, parameter)) { + OnWaitForPresent(); OnPresent(); } } - - renderStopwatch.Stop(); } /// @@ -225,8 +263,7 @@ partial class SwapChainManager Stopwatch renderStopwatch = this.renderStopwatch ??= new(); Stopwatch frameStopwatch = new(); CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; - - DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + DynamicResolutionManager frameTimeWatcher = new(60); if (!OnFrameRequest(out object? parameter, cancellationToken)) { @@ -237,6 +274,7 @@ partial class SwapChainManager if (OnUpdate(renderStopwatch.Elapsed, parameter)) { + OnWaitForPresent(); OnPresent(); } @@ -255,6 +293,18 @@ partial class SwapChainManager 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 @@ -264,8 +314,6 @@ partial class SwapChainManager } } } - - renderStopwatch.Stop(); } /// @@ -328,6 +376,11 @@ partial class SwapChainManager return this.shaderRunner!.TryExecute(this.texture!, time, parameter); } + /// + /// Waits for the panel to be ready to present a new frame for the current application. + /// + private unsafe partial void OnWaitForPresent(); + /// /// Presents the last rendered frame for the current application. /// diff --git a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs index 4021ed1f..2d3fd60b 100644 --- a/src/ComputeSharp.UI/Helpers/SwapChainManager.cs +++ b/src/ComputeSharp.UI/Helpers/SwapChainManager.cs @@ -175,6 +175,11 @@ internal sealed unsafe partial class SwapChainManager : NativeObject /// private volatile bool isDynamicResolutionEnabled; + /// + /// The flags to enable or disable vertical sync. + /// + private volatile uint syncInterval; + /// /// The instance tracking time since the first rendered frame. /// @@ -384,12 +389,15 @@ internal sealed unsafe partial class SwapChainManager : NativeObject } } + /// + private unsafe partial void OnWaitForPresent() + { + _ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, Win32.INFINITE, true); + } + /// private unsafe partial void OnPresent() { - // 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 @@ -455,7 +463,7 @@ internal sealed unsafe partial class SwapChainManager : NativeObject this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), updatedFenceValue).Assert(); // Present the new frame - this.dxgiSwapChain3.Get()->Present(0, 0).Assert(); + this.dxgiSwapChain3.Get()->Present(SyncInterval: this.syncInterval, 0).Assert(); if (updatedFenceValue > this.d3D12Fence.Get()->GetCompletedValue()) {