Merge pull request #197 from Sergio0694/feature/vertical-sync

Add vertical sync option
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2022-01-22 14:54:08 +01:00
コミット f906dbaae0
13ファイル変更
+192 -45

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

+1
ファイルの表示
@@ -5,6 +5,7 @@
/// </summary>
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";
+18
ファイルの表示
@@ -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
/// </summary>
public IList<int> ResolutionScaleOptions { get; } = new[] { 25, 50, 75, 100 };
private bool isVerticalSyncEnabled;
/// <summary>
/// Gets or sets whether the vertical sync is enabled.
/// </summary>
public bool IsVerticalSyncEnabled
{
get => this.isVerticalSyncEnabled;
set
{
if (SetProperty(ref this.isVerticalSyncEnabled, value))
{
this.analyticsService.Log(Event.IsVerticalSyncEnabledChanged, (nameof(value), value));
}
}
}
private bool isDynamicResolutionEnabled;
/// <summary>
+5 -1
ファイルの表示
@@ -1,4 +1,8 @@
<Application
x:Class="ComputeSharp.SwapChain.Uwp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" />
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
</Application.Resources>
</Application>
+5 -2
ファイルの表示
@@ -208,10 +208,10 @@
<Version>7.1.2</Version>
</PackageReference>
<PackageReference Include="Microsoft.AppCenter.Analytics">
<Version>4.4.0</Version>
<Version>4.5.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.AppCenter.Crashes">
<Version>4.4.0</Version>
<Version>4.5.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection">
<Version>6.0.0</Version>
@@ -225,6 +225,9 @@
<PackageReference Include="Microsoft.Toolkit.Uwp.UI.Media">
<Version>7.1.2</Version>
</PackageReference>
<PackageReference Include="Microsoft.UI.Xaml">
<Version>2.7.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
+2
ファイルの表示
@@ -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 @@
<SymbolIcon Symbol="Setting" />
<Button.Flyout>
<MenuFlyout>
<ToggleMenuFlyoutItem IsChecked="{x:Bind ViewModel.IsVerticalSyncEnabled, Mode=TwoWay}" Text="Vertical sync" />
<ToggleMenuFlyoutItem IsChecked="{x:Bind ViewModel.IsDynamicResolutionEnabled, Mode=TwoWay}" Text="Dynamic resolution" />
<MenuFlyoutSeparator />
<ToggleMenuFlyoutItem
+1
ファイルの表示
@@ -150,6 +150,7 @@
<computesharp:AnimatedComputeShaderPanel
x:Name="ShaderPanel"
Grid.Row="1"
IsVerticalSyncEnabled="{x:Bind ViewModel.IsVerticalSyncEnabled, Mode=OneWay}"
IsDynamicResolutionEnabled="{x:Bind ViewModel.IsDynamicResolutionEnabled, Mode=OneWay}"
IsPaused="{x:Bind ViewModel.IsRenderingPaused, Mode=OneWay}"
ResolutionScale="{x:Bind converters:ResolutionScaleConverter.ConvertPercentageToScale(ViewModel.SelectedResolutionScale), Mode=OneWay}"
+28
ファイルの表示
@@ -135,6 +135,34 @@ partial class AnimatedComputeShaderPanel
@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)
{
var @this = (AnimatedComputeShaderPanel)d;
var isVerticalSyncEnabled = (bool)e.NewValue;
@this.swapChainManager.QueueVerticalSyncModeChange(isVerticalSyncEnabled);
}
/// <summary>
/// Gets or sets whether or not the rendering is paused.
/// </summary>
+1
ファイルの表示
@@ -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)
+28
ファイルの表示
@@ -169,4 +169,32 @@ partial class ComputeShaderPanel
@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)
{
var @this = (ComputeShaderPanel)d;
var isVerticalSyncEnabled = (bool)e.NewValue;
@this.swapChainManager.QueueVerticalSyncModeChange(isVerticalSyncEnabled);
}
}
+1
ファイルの表示
@@ -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)
+31 -32
ファイルの表示
@@ -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;
/// </summary>
internal unsafe ref struct DynamicResolutionManager
{
/// <summary>
/// The target frame time in ticks to reach 60fps (set to 64fps).
/// </summary>
public const long TargetFrameTimeInTicksFor60fps = 156250;
/// <summary>
/// The upper frame time threshold in ticks to reach 60fps.
/// </summary>
private const long UpperFrameTimeThresholdInTicksFor60fps = 166666;
/// <summary>
/// The lower frame time threshold in ticks to reach 60fps (set to 68fps).
/// </summary>
private const long LowerFrameTimeThresholdInTicksFor60fps = 147058;
/// <summary>
/// The size of the sliding frame time window to monitor frame times.
/// </summary>
@@ -45,6 +28,21 @@ internal unsafe ref struct DynamicResolutionManager
/// </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>
@@ -68,20 +66,20 @@ internal unsafe ref struct DynamicResolutionManager
/// <summary>
/// Initializes a new <see cref="DynamicResolutionManager"/> instance.
/// </summary>
/// <param name="manager">The resulting <see cref="DynamicResolutionManager"/> instance.</param>
public static void Create(out DynamicResolutionManager manager)
/// <param name="targetFramerate">The target framerate to use.</param>
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<long>(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<long>(Unsafe.AsPointer(ref this.frameTimesInTicks[0]), SlidingFrameTimeWindowLength).Fill(targetFrameTimeInTicks);
}
/// <summary>
@@ -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);
+59 -6
ファイルの表示
@@ -97,6 +97,40 @@ partial class SwapChainManager<TOwner>
}
}
/// <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)
{
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<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>
@@ -160,10 +194,14 @@ partial class SwapChainManager<TOwner>
RenderLoop();
}
this.renderStopwatch?.Stop();
OnRenderingStopped();
}
catch (Exception e)
{
this.renderStopwatch?.Stop();
OnRenderingFailed(e);
}
finally
@@ -192,6 +230,7 @@ partial class SwapChainManager<TOwner>
// 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<TOwner>
if (OnUpdate(renderStopwatch.Elapsed, parameter))
{
OnWaitForPresent();
OnPresent();
}
}
renderStopwatch.Stop();
}
/// <summary>
@@ -225,8 +263,7 @@ partial class SwapChainManager<TOwner>
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<TOwner>
if (OnUpdate(renderStopwatch.Elapsed, parameter))
{
OnWaitForPresent();
OnPresent();
}
@@ -255,6 +293,18 @@ partial class SwapChainManager<TOwner>
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<TOwner>
}
}
}
renderStopwatch.Stop();
}
/// <summary>
@@ -328,6 +376,11 @@ partial class SwapChainManager<TOwner>
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>
+12 -4
ファイルの表示
@@ -175,6 +175,11 @@ internal sealed unsafe partial class SwapChainManager<TOwner> : NativeObject
/// </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>
@@ -384,12 +389,15 @@ internal sealed unsafe partial class SwapChainManager<TOwner> : NativeObject
}
}
/// <inheritdoc/>
private unsafe partial void OnWaitForPresent()
{
_ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, Win32.INFINITE, true);
}
/// <inheritdoc/>
private unsafe partial void OnPresent()
{
// Wait for the swap chain to be ready for presenting
_ = Win32.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, true);
using ComPtr<ID3D12Resource> d3D12Resource = default;
// Get the underlying ID3D12Resource pointer for the texture
@@ -455,7 +463,7 @@ internal sealed unsafe partial class SwapChainManager<TOwner> : 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())
{