From f2d410f270fd9745c9e2ba9325f5804b30dbdd71 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 31 Oct 2021 19:22:28 +0100 Subject: [PATCH] Switched WinUI projects to file-scoped namespaces --- .../ComputeSharp.SwapChain.WinUI/App.xaml.cs | 45 +- .../Converters/RenderingPauseConverter.cs | 23 +- .../Converters/ResolutionScaleConverter.cs | 41 +- .../Models/ComputeShader.cs | 61 +- .../Shaders/Runners/ContouredLayersRunner.cs | 33 +- .../ViewModels/MainViewModel.cs | 175 ++-- .../Views/MainWindow.xaml.cs | 43 +- .../Controls/ComputeShaderPanel.Properties.cs | 217 ++-- .../Controls/ComputeShaderPanel.Rendering.cs | 925 +++++++++--------- .../Controls/ComputeShaderPanel.cs | 105 +- .../Helpers/DynamicResolutionManager.cs | 225 +++-- src/ComputeSharp.WinUI/IShaderRunner.cs | 21 +- src/ComputeSharp.WinUI/ShaderRunner{T}.cs | 63 +- 13 files changed, 982 insertions(+), 995 deletions(-) diff --git a/samples/ComputeSharp.SwapChain.WinUI/App.xaml.cs b/samples/ComputeSharp.SwapChain.WinUI/App.xaml.cs index 014d74cb..277cdff4 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/App.xaml.cs +++ b/samples/ComputeSharp.SwapChain.WinUI/App.xaml.cs @@ -1,33 +1,32 @@ using ComputeSharp.SwapChain.WinUI.Views; using Microsoft.UI.Xaml; -namespace ComputeSharp.SwapChain.WinUI +namespace ComputeSharp.SwapChain.WinUI; + +/// +/// Provides application-specific behavior to supplement the default Application class. +/// +public partial class App : Application { /// - /// Provides application-specific behavior to supplement the default Application class. + /// The main application window /// - public partial class App : Application + private Window? mainWindow; + + /// + /// Initializes the singleton application object. This is the first line of authored code + /// executed, and as such is the logical equivalent of main() or WinMain(). + /// + public App() { - /// - /// The main application window - /// - private Window? mainWindow; + this.InitializeComponent(); + } - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - } - - /// - protected override void OnLaunched(LaunchActivatedEventArgs args) - { - mainWindow = new MainWindow(); - mainWindow.Closed += (_, _) => Exit(); - mainWindow.Activate(); - } + /// + protected override void OnLaunched(LaunchActivatedEventArgs args) + { + mainWindow = new MainWindow(); + mainWindow.Closed += (_, _) => Exit(); + mainWindow.Activate(); } } diff --git a/samples/ComputeSharp.SwapChain.WinUI/Converters/RenderingPauseConverter.cs b/samples/ComputeSharp.SwapChain.WinUI/Converters/RenderingPauseConverter.cs index 53493e7f..5c8ae0bf 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/Converters/RenderingPauseConverter.cs +++ b/samples/ComputeSharp.SwapChain.WinUI/Converters/RenderingPauseConverter.cs @@ -1,20 +1,19 @@ using Microsoft.UI.Xaml.Controls; -namespace ComputeSharp.SwapChain.WinUI.Converters +namespace ComputeSharp.SwapChain.WinUI.Converters; + +/// +/// A class with some static converters for rendering state. +/// +public static class RenderingPauseConverter { /// - /// A class with some static converters for rendering state. + /// Gets a symbol for an input rendering state. /// - public static class RenderingPauseConverter + /// Whether or not the rendering is currently paaused. + /// A symbol representing the next action for the rendering. + public static Symbol ConvertPausedToSymbol(bool value) { - /// - /// Gets a symbol for an input rendering state. - /// - /// Whether or not the rendering is currently paaused. - /// A symbol representing the next action for the rendering. - public static Symbol ConvertPausedToSymbol(bool value) - { - return value ? Symbol.Play : Symbol.Pause; - } + return value ? Symbol.Play : Symbol.Pause; } } diff --git a/samples/ComputeSharp.SwapChain.WinUI/Converters/ResolutionScaleConverter.cs b/samples/ComputeSharp.SwapChain.WinUI/Converters/ResolutionScaleConverter.cs index de1408b4..1d242fc7 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/Converters/ResolutionScaleConverter.cs +++ b/samples/ComputeSharp.SwapChain.WinUI/Converters/ResolutionScaleConverter.cs @@ -1,28 +1,27 @@ -namespace ComputeSharp.SwapChain.WinUI.Converters +namespace ComputeSharp.SwapChain.WinUI.Converters; + +/// +/// A class with some static converters for resolution scale settings. +/// +public static class ResolutionScaleConverter { /// - /// A class with some static converters for resolution scale settings. + /// Converts a resolution scale to a formatted string. /// - public static class ResolutionScaleConverter + /// The input resolution scale (in percentage). + /// A formatted percentage string for . + public static string ConvertPercentageToFormattedString(int value) { - /// - /// Converts a resolution scale to a formatted string. - /// - /// The input resolution scale (in percentage). - /// A formatted percentage string for . - public static string ConvertPercentageToFormattedString(int value) - { - return $"{value}%"; - } + return $"{value}%"; + } - /// - /// Converts a percentage value to a scaled value in the [0, 1] range. - /// - /// The input percentage value to scale. - /// The input percentage scaled to the [0, 1] range. - public static double ConvertPercentageToScale(int value) - { - return value / 100.0; - } + /// + /// Converts a percentage value to a scaled value in the [0, 1] range. + /// + /// The input percentage value to scale. + /// The input percentage scaled to the [0, 1] range. + public static double ConvertPercentageToScale(int value) + { + return value / 100.0; } } diff --git a/samples/ComputeSharp.SwapChain.WinUI/Models/ComputeShader.cs b/samples/ComputeSharp.SwapChain.WinUI/Models/ComputeShader.cs index dc5e108f..9816232b 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/Models/ComputeShader.cs +++ b/samples/ComputeSharp.SwapChain.WinUI/Models/ComputeShader.cs @@ -1,44 +1,43 @@ using CommunityToolkit.Mvvm.ComponentModel; using ComputeSharp.WinUI; -namespace ComputeSharp.SwapChain.WinUI.Models +namespace ComputeSharp.SwapChain.WinUI.Models; + +/// +/// A model for a compute shader. +/// +/// This can be converted to a record when bindings are fixed, see notes in the XAML code. +public sealed class ComputeShader : ObservableObject { /// - /// A model for a compute shader. + /// Creates a new instance. /// - /// This can be converted to a record when bindings are fixed, see notes in the XAML code. - public sealed class ComputeShader : ObservableObject + /// The name of the shader. + /// The instance to execute. + public ComputeShader(string name, IShaderRunner shaderRunner) { - /// - /// Creates a new instance. - /// - /// The name of the shader. - /// The instance to execute. - public ComputeShader(string name, IShaderRunner shaderRunner) - { - Name = name; - ShaderRunner = shaderRunner; - } + Name = name; + ShaderRunner = shaderRunner; + } - /// - /// Gets the name of the shader. - /// - public string Name { get; } + /// + /// Gets the name of the shader. + /// + public string Name { get; } - /// - /// Gets the instance to execute. - /// - public IShaderRunner ShaderRunner { get; } + /// + /// Gets the instance to execute. + /// + public IShaderRunner ShaderRunner { get; } - private bool isSelected; + private bool isSelected; - /// - /// Gets or sets whether the current shader is selected. - /// - public bool IsSelected - { - get => this.isSelected; - set => SetProperty(ref this.isSelected, value); - } + /// + /// Gets or sets whether the current shader is selected. + /// + public bool IsSelected + { + get => this.isSelected; + set => SetProperty(ref this.isSelected, value); } } diff --git a/samples/ComputeSharp.SwapChain.WinUI/Shaders/Runners/ContouredLayersRunner.cs b/samples/ComputeSharp.SwapChain.WinUI/Shaders/Runners/ContouredLayersRunner.cs index 6930f5a4..1a09c53a 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/Shaders/Runners/ContouredLayersRunner.cs +++ b/samples/ComputeSharp.SwapChain.WinUI/Shaders/Runners/ContouredLayersRunner.cs @@ -4,29 +4,28 @@ using ComputeSharp.SwapChain.Shaders; using ComputeSharp.WinUI; using Windows.ApplicationModel; -namespace ComputeSharp.SwapChain.WinUI.Shaders.Runners +namespace ComputeSharp.SwapChain.WinUI.Shaders.Runners; + +/// +/// A specialized for . +/// +public sealed class ContouredLayersRunner : IShaderRunner { /// - /// A specialized for . + /// A texture for \Textures\RustyMetal.png. /// - public sealed class ContouredLayersRunner : IShaderRunner + private ReadOnlyTexture2D? texture; + + /// + public void Execute(IReadWriteTexture2D texture, TimeSpan timespan) { - /// - /// A texture for \Textures\RustyMetal.png. - /// - private ReadOnlyTexture2D? texture; - - /// - public void Execute(IReadWriteTexture2D texture, TimeSpan timespan) + if (this.texture is null) { - if (this.texture is null) - { - string filename = Path.Combine(Package.Current.InstalledLocation.Path, "Assets", "Textures", "RustyMetal.png"); + string filename = Path.Combine(Package.Current.InstalledLocation.Path, "Assets", "Textures", "RustyMetal.png"); - this.texture = Gpu.Default.LoadReadOnlyTexture2D(filename); - } - - Gpu.Default.ForEach(texture, new ContouredLayers((float)timespan.TotalSeconds, this.texture)); + this.texture = Gpu.Default.LoadReadOnlyTexture2D(filename); } + + Gpu.Default.ForEach(texture, new ContouredLayers((float)timespan.TotalSeconds, this.texture)); } } diff --git a/samples/ComputeSharp.SwapChain.WinUI/ViewModels/MainViewModel.cs b/samples/ComputeSharp.SwapChain.WinUI/ViewModels/MainViewModel.cs index f994457c..0340006a 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/ViewModels/MainViewModel.cs +++ b/samples/ComputeSharp.SwapChain.WinUI/ViewModels/MainViewModel.cs @@ -6,72 +6,72 @@ using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using ComputeSharp.SwapChain.WinUI.Shaders.Runners; -namespace ComputeSharp.SwapChain.WinUI.ViewModels +namespace ComputeSharp.SwapChain.WinUI.ViewModels; + +/// +/// The viewmodel for for a view that allows users to select shaders and customize settings. +/// +public sealed class MainViewModel : ObservableObject { /// - /// The viewmodel for for a view that allows users to select shaders and customize settings. + /// Creates a new instance. /// - public sealed class MainViewModel : ObservableObject + public MainViewModel() { - /// - /// Creates a new instance. - /// - public MainViewModel() - { - this.isDynamicResolutionEnabled = true; - this.selectedResolutionScale = 100; - this.selectedComputeShader = ComputeShaderOptions[0]; - this.selectedComputeShader.IsSelected = true; + this.isDynamicResolutionEnabled = true; + this.selectedResolutionScale = 100; + this.selectedComputeShader = ComputeShaderOptions[0]; + this.selectedComputeShader.IsSelected = true; - SetResolutionScaleCommand = new RelayCommand(SetResolutionScale); - ToggleRenderingPausedCommand = new RelayCommand(ToggleRenderingPaused); - } + SetResolutionScaleCommand = new RelayCommand(SetResolutionScale); + ToggleRenderingPausedCommand = new RelayCommand(ToggleRenderingPaused); + } - /// - /// Gets the available resolution scaling options (as percentage values). - /// - public IList ResolutionScaleOptions { get; } = new[] { 25, 50, 75, 100 }; + /// + /// Gets the available resolution scaling options (as percentage values). + /// + public IList ResolutionScaleOptions { get; } = new[] { 25, 50, 75, 100 }; - private bool isDynamicResolutionEnabled; + private bool isDynamicResolutionEnabled; - /// - /// Gets or sets whether the dynamic resolution is enabled. - /// - public bool IsDynamicResolutionEnabled - { - get => this.isDynamicResolutionEnabled; - set => SetProperty(ref this.isDynamicResolutionEnabled, value); - } + /// + /// Gets or sets whether the dynamic resolution is enabled. + /// + public bool IsDynamicResolutionEnabled + { + get => this.isDynamicResolutionEnabled; + set => SetProperty(ref this.isDynamicResolutionEnabled, value); + } - private int selectedResolutionScale; + private int selectedResolutionScale; - /// - /// Gets the currently selected resolution scale setting (as percentage valaue). - /// - public int SelectedResolutionScale - { - get => this.selectedResolutionScale; - private set => SetProperty(ref this.selectedResolutionScale, value); - } + /// + /// Gets the currently selected resolution scale setting (as percentage valaue). + /// + public int SelectedResolutionScale + { + get => this.selectedResolutionScale; + private set => SetProperty(ref this.selectedResolutionScale, value); + } - /// - /// Gets the command that sets . - /// - public IRelayCommand SetResolutionScaleCommand { get; } + /// + /// Gets the command that sets . + /// + public IRelayCommand SetResolutionScaleCommand { get; } - /// - /// Sets . - /// - private void SetResolutionScale(int resolutionScale) - { - SelectedResolutionScale = resolutionScale; - } + /// + /// Sets . + /// + private void SetResolutionScale(int resolutionScale) + { + SelectedResolutionScale = resolutionScale; + } - /// - /// Gets the collection of available compute shader. - /// - public IReadOnlyList ComputeShaderOptions { get; } = new ComputeShader[] - { + /// + /// Gets the collection of available compute shader. + /// + public IReadOnlyList ComputeShaderOptions { get; } = new ComputeShader[] + { new("Colorful infinity", new ShaderRunner(static time => new((float)time.TotalSeconds))), new("Extruded truchet", new ShaderRunner(static time => new((float)time.TotalSeconds))), new("Fractal tiling", new ShaderRunner(static time => new((float)time.TotalSeconds))), @@ -82,50 +82,49 @@ namespace ComputeSharp.SwapChain.WinUI.ViewModels new("Pyramid pattern", new ShaderRunner(static time => new((float)time.TotalSeconds))), new("Triangle grid contouring", new ShaderRunner(static time => new((float)time.TotalSeconds))), new("Contoured layers", new ContouredLayersRunner()) - }; + }; - private ComputeShader selectedComputeShader; + private ComputeShader selectedComputeShader; - /// - /// Gets or sets the currently selected compute shader. - /// - public ComputeShader SelectedComputeShader + /// + /// Gets or sets the currently selected compute shader. + /// + public ComputeShader SelectedComputeShader + { + get => this.selectedComputeShader; + set { - get => this.selectedComputeShader; - set - { - this.selectedComputeShader.IsSelected = false; + this.selectedComputeShader.IsSelected = false; - if (SetProperty(ref this.selectedComputeShader, value) && - value is not null) - { - value.IsSelected = true; - } + if (SetProperty(ref this.selectedComputeShader, value) && + value is not null) + { + value.IsSelected = true; } } + } - private bool isRenderingPaused; + private bool isRenderingPaused; - /// - /// Gets or sets whether the rendering is currently paused. - /// - public bool IsRenderingPaused - { - get => this.isRenderingPaused; - set => SetProperty(ref this.isRenderingPaused, value); - } + /// + /// Gets or sets whether the rendering is currently paused. + /// + public bool IsRenderingPaused + { + get => this.isRenderingPaused; + set => SetProperty(ref this.isRenderingPaused, value); + } - /// - /// Gets the command that toggles . - /// - public IRelayCommand ToggleRenderingPausedCommand { get; } + /// + /// Gets the command that toggles . + /// + public IRelayCommand ToggleRenderingPausedCommand { get; } - /// - /// Toggles . - /// - private void ToggleRenderingPaused() - { - IsRenderingPaused = !IsRenderingPaused; - } + /// + /// Toggles . + /// + private void ToggleRenderingPaused() + { + IsRenderingPaused = !IsRenderingPaused; } } diff --git a/samples/ComputeSharp.SwapChain.WinUI/Views/MainWindow.xaml.cs b/samples/ComputeSharp.SwapChain.WinUI/Views/MainWindow.xaml.cs index f39fe566..c9ce9c54 100644 --- a/samples/ComputeSharp.SwapChain.WinUI/Views/MainWindow.xaml.cs +++ b/samples/ComputeSharp.SwapChain.WinUI/Views/MainWindow.xaml.cs @@ -1,32 +1,31 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Input; -namespace ComputeSharp.SwapChain.WinUI.Views +namespace ComputeSharp.SwapChain.WinUI.Views; + +/// +/// A view for . +/// +public sealed partial class MainWindow : Window { - /// - /// A view for . - /// - public sealed partial class MainWindow : Window + public MainWindow() { - public MainWindow() - { - this.InitializeComponent(); - this.ExtendsContentIntoTitleBar = true; + this.InitializeComponent(); + this.ExtendsContentIntoTitleBar = true; - SetTitleBar(TitleBarRectangle); - } + SetTitleBar(TitleBarRectangle); + } - // Opens the shader selection panel - private void OpenShaderSelectionPanelButton_Click(object sender, RoutedEventArgs e) - { - Root.Resources.Remove("ShaderSelectionPanel"); - Root.Children.Add(ShaderSelectionPanel); - } + // Opens the shader selection panel + private void OpenShaderSelectionPanelButton_Click(object sender, RoutedEventArgs e) + { + Root.Resources.Remove("ShaderSelectionPanel"); + Root.Children.Add(ShaderSelectionPanel); + } - // Hides the shader selection panel - private void ShaderSelectionPanel_Tapped(object sender, TappedRoutedEventArgs e) - { - Root.Children.Remove(ShaderSelectionPanel); - } + // Hides the shader selection panel + private void ShaderSelectionPanel_Tapped(object sender, TappedRoutedEventArgs e) + { + Root.Children.Remove(ShaderSelectionPanel); } } diff --git a/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.Properties.cs b/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.Properties.cs index 5ec75de6..2714afd8 100644 --- a/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.Properties.cs +++ b/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.Properties.cs @@ -1,124 +1,123 @@ using System; using Microsoft.UI.Xaml; -namespace ComputeSharp.WinUI +namespace ComputeSharp.WinUI; + +/// +public sealed unsafe partial class ComputeShaderPanel { - /// - public sealed unsafe partial class ComputeShaderPanel + /// + /// Gets or sets the instance to use to render content. + /// + public IShaderRunner? ShaderRunner { - /// - /// Gets or sets the instance to use to render content. - /// - public IShaderRunner? ShaderRunner + get => (IShaderRunner?)GetValue(ShaderFactoryProperty); + set => SetValue(ShaderFactoryProperty, value); + } + + /// + /// The backing . + /// + public static readonly DependencyProperty ShaderFactoryProperty = DependencyProperty.Register( + nameof(ShaderRunner), + typeof(IShaderRunner), + typeof(ComputeShaderPanel), + new PropertyMetadata(null, static (d, e) => ((ComputeShaderPanel)d).shaderRunner = (IShaderRunner?)e.NewValue)); + + /// + /// 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(ComputeShaderPanel), + new PropertyMetadata(1.0, OnResolutionScalePropertyChanged)); + + /// + private static void OnResolutionScalePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var @this = (ComputeShaderPanel)d; + var resolutionScale = (double)e.NewValue; + + @this.targetResolutionScale = (float)resolutionScale; + + if (!@this.isDynamicResolutionEnabled) { - get => (IShaderRunner?)GetValue(ShaderFactoryProperty); - set => SetValue(ShaderFactoryProperty, value); + @this.OnResize(); } + } - /// - /// The backing . - /// - public static readonly DependencyProperty ShaderFactoryProperty = DependencyProperty.Register( - nameof(ShaderRunner), - typeof(IShaderRunner), - typeof(ComputeShaderPanel), - new PropertyMetadata(null, static (d, e) => ((ComputeShaderPanel)d).shaderRunner = (IShaderRunner?)e.NewValue)); + /// + /// 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); + } - /// - /// 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 + /// + /// The backing . + /// + public static readonly DependencyProperty IsDynamicResolutionEnabledProperty = DependencyProperty.Register( + nameof(IsDynamicResolutionEnabled), + typeof(bool), + typeof(ComputeShaderPanel), + new PropertyMetadata(true, OnIsDynamicResolutionEnabledPropertyChanged)); + + /// + private static void OnIsDynamicResolutionEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + 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) { - get => (double)GetValue(ResolutionScaleProperty); - set => SetValue(ResolutionScaleProperty, Math.Clamp(value, 0.1, 1.0)); + @this.OnStopRenderLoop(); } - - /// - /// The backing . - /// - public static readonly DependencyProperty ResolutionScaleProperty = DependencyProperty.Register( - nameof(ResolutionScale), - typeof(double), - typeof(ComputeShaderPanel), - new PropertyMetadata(1.0, OnResolutionScalePropertyChanged)); - - /// - private static void OnResolutionScalePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + else { - var @this = (ComputeShaderPanel)d; - var resolutionScale = (double)e.NewValue; - - @this.targetResolutionScale = (float)resolutionScale; - - if (!@this.isDynamicResolutionEnabled) - { - @this.OnResize(); - } - } - - /// - /// 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(ComputeShaderPanel), - new PropertyMetadata(true, OnIsDynamicResolutionEnabledPropertyChanged)); - - /// - private static void OnIsDynamicResolutionEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - 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.OnStartRenderLoop(); } } } diff --git a/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.Rendering.cs b/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.Rendering.cs index d043d379..433e176e 100644 --- a/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.Rendering.cs +++ b/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.Rendering.cs @@ -10,518 +10,517 @@ using FX = TerraFX.Interop.Windows; #pragma warning disable CS0420 -namespace ComputeSharp.WinUI +namespace ComputeSharp.WinUI; + +/// +public sealed partial class ComputeShaderPanel { - /// - public sealed partial class ComputeShaderPanel + /// + /// The render thread in use, if any. + /// + private Thread? renderThread; + + /// + /// The instance used to create shaders to run. + /// + private IShaderRunner? shaderRunner; + + /// + /// The pointer for the device currently in use. + /// + private ComPtr d3D12Device; + + /// + /// The instance to use for graphics operations. + /// + private ComPtr d3D12CommandQueue; + + /// + /// The instance used for graphics operations. + /// + private ComPtr d3D12Fence; + + /// + /// The next fence value for graphics operations using . + /// + private ulong nextD3D12FenceValue = 1; + + /// + /// The object to create command lists. + /// + private ComPtr d3D12CommandAllocator; + + /// + /// The instance used to copy data to the back buffers. + /// + private ComPtr d3D12GraphicsCommandList; + + /// + /// The instance used to display content onto the target window. + /// + private ComPtr dxgiSwapChain2; + + /// + /// The awaitable object for calls. + /// + private IntPtr frameLatencyWaitableObject; + + /// + /// The first buffer within . + /// + private ComPtr d3D12Resource0; + + /// + /// The second buffer within . + /// + private ComPtr d3D12Resource1; + + /// + /// The index of the next buffer that can be used to present content. + /// + private uint currentBufferIndex; + + /// + /// The instance used to prepare frames to display. + /// + private ReadWriteTexture2D? texture; + + /// + /// Whether or not the window has been resized and requires the buffers to be updated. + /// + private volatile bool isResizePending; + + /// + /// The backing store for for the render thread. + /// + private volatile float width; + + /// + /// The backing store for for the render thread. + /// + private volatile float height; + + /// + /// The backing store for for the render thread. + /// + private volatile float compositionScaleX; + + /// + /// The backing store for for the render thread. + /// + private volatile float compositionScaleY; + + /// + /// The resolution scale used to render frames when explicitly controlled by the user. + /// + private volatile float resolutionScale; + + /// + /// The resolution scale used to render frames, in either render mode. + /// + private volatile float targetResolutionScale; + + /// + /// Whether dynamic resolution is currently enabled. + /// + 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; + + /// + /// Indicates whether or not has already been called. + /// + private bool isInitialized; + + /// + /// Initializes the current application. + /// + private unsafe void OnInitialize() { - /// - /// The render thread in use, if any. - /// - private Thread? renderThread; - - /// - /// The instance used to create shaders to run. - /// - private IShaderRunner? shaderRunner; - - /// - /// The pointer for the device currently in use. - /// - private ComPtr d3D12Device; - - /// - /// The instance to use for graphics operations. - /// - private ComPtr d3D12CommandQueue; - - /// - /// The instance used for graphics operations. - /// - private ComPtr d3D12Fence; - - /// - /// The next fence value for graphics operations using . - /// - private ulong nextD3D12FenceValue = 1; - - /// - /// The object to create command lists. - /// - private ComPtr d3D12CommandAllocator; - - /// - /// The instance used to copy data to the back buffers. - /// - private ComPtr d3D12GraphicsCommandList; - - /// - /// The instance used to display content onto the target window. - /// - private ComPtr dxgiSwapChain2; - - /// - /// The awaitable object for calls. - /// - private IntPtr frameLatencyWaitableObject; - - /// - /// The first buffer within . - /// - private ComPtr d3D12Resource0; - - /// - /// The second buffer within . - /// - private ComPtr d3D12Resource1; - - /// - /// The index of the next buffer that can be used to present content. - /// - private uint currentBufferIndex; - - /// - /// The instance used to prepare frames to display. - /// - private ReadWriteTexture2D? texture; - - /// - /// Whether or not the window has been resized and requires the buffers to be updated. - /// - private volatile bool isResizePending; - - /// - /// The backing store for for the render thread. - /// - private volatile float width; - - /// - /// The backing store for for the render thread. - /// - private volatile float height; - - /// - /// The backing store for for the render thread. - /// - private volatile float compositionScaleX; - - /// - /// The backing store for for the render thread. - /// - private volatile float compositionScaleY; - - /// - /// The resolution scale used to render frames when explicitly controlled by the user. - /// - private volatile float resolutionScale; - - /// - /// The resolution scale used to render frames, in either render mode. - /// - private volatile float targetResolutionScale; - - /// - /// Whether dynamic resolution is currently enabled. - /// - 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; - - /// - /// Indicates whether or not has already been called. - /// - private bool isInitialized; - - /// - /// Initializes the current application. - /// - private unsafe void OnInitialize() + if (this.isInitialized) { - if (this.isInitialized) - { - return; - } - - this.isInitialized = true; - - // Get the underlying ID3D12Device in use - fixed (ID3D12Device** d3D12Device = this.d3D12Device) - { - InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof(), (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, - FX.__uuidof(), - (void**)d3D12CommandQueue).Assert(); - } - - // Create the direct fence - fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence) - { - this.d3D12Device.Get()->CreateFence( - 0, - D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE, - FX.__uuidof(), - (void**)d3D12Fence).Assert(); - } - - // Create the swap chain to display frames - using (ComPtr dxgiFactory2 = default) - { - FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof(), (void**)dxgiFactory2.GetAddressOf()).Assert(); - - 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 = (uint)Math.Max(Math.Ceiling(this.width * this.compositionScaleX * this.targetResolutionScale), 1.0); - dxgiSwapChainDesc1.Height = (uint)Math.Max(Math.Ceiling(this.height * this.compositionScaleY * this.targetResolutionScale), 1.0); - 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 = FX.DXGI_USAGE_RENDER_TARGET_OUTPUT; - - using ComPtr dxgiSwapChain1 = default; - - dxgiFactory2.Get()->CreateSwapChainForComposition( - (IUnknown*)this.d3D12CommandQueue.Get(), - &dxgiSwapChainDesc1, - null, - (IDXGISwapChain1**)&dxgiSwapChain1).Assert(); - - fixed (IDXGISwapChain2** dxgiSwapChain2 = this.dxgiSwapChain2) - { - dxgiSwapChain1.CopyTo(dxgiSwapChain2).Assert(); - } - } - - // Get the awaitable object to synchronizize present calls - this.frameLatencyWaitableObject = this.dxgiSwapChain2.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, - FX.__uuidof(), - (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, - null, - FX.__uuidof(), - (void**)d3D12GraphicsCommandList).Assert(); - } - - // 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; - - 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(); - - using ComPtr idxgiSwapChain = default; - - this.dxgiSwapChain2.CopyTo(&idxgiSwapChain).Assert(); - - swapChainPanelNative.Get()->SetSwapChain(idxgiSwapChain.Get()).Assert(); - - GC.KeepAlive(this); + return; } - /// - /// Resizes the current application. - /// - private void OnResize() + this.isInitialized = true; + + // Get the underlying ID3D12Device in use + fixed (ID3D12Device** d3D12Device = this.d3D12Device) { - this.isResizePending = true; + InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof(), (void**)d3D12Device).Assert(); } - /// - /// Applies the actual resize logic that was scheduled from . - /// - private unsafe void ApplyResize() + // Create the direct command queue to use + fixed (ID3D12CommandQueue** d3D12CommandQueue = this.d3D12CommandQueue) { - this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue).Assert(); + 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; - // Wait for the fence again to ensure there are no pending operations - this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default).Assert(); - - this.nextD3D12FenceValue++; - - // Dispose the old buffers before resizing the buffer - this.d3D12Resource0.Dispose(); - this.d3D12Resource1.Dispose(); - - // Resize the swap chain buffers - this.dxgiSwapChain2.Get()->ResizeBuffers( - 2, - (uint)Math.Max(Math.Ceiling(this.width * this.compositionScaleX * this.targetResolutionScale), 1.0), - (uint)Math.Max(Math.Ceiling(this.height * this.compositionScaleY * this.targetResolutionScale), 1.0), - 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 / this.targetResolutionScale); - transformMatrix._22 = (1 / this.compositionScaleY) * (1 / this.targetResolutionScale); - - this.dxgiSwapChain2.Get()->SetMatrixTransform(&transformMatrix).Assert(); - - // Retrieve the back buffers for the swap chain - fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0) - fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1) - { - this.dxgiSwapChain2.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0).Assert(); - this.dxgiSwapChain2.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1).Assert(); - } - - // Get the index of the initial back buffer - using (ComPtr dxgiSwapChain3 = default) - { - this.dxgiSwapChain2.CopyTo(dxgiSwapChain3.GetAddressOf()).Assert(); - - this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); - } - - this.texture?.Dispose(); - - D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); - - // Create the 2D texture to use to generate frames to display - this.texture = Gpu.Default.AllocateReadWriteTexture2D( - (int)d3D12Resource0Description.Width, - (int)d3D12Resource0Description.Height); + this.d3D12Device.Get()->CreateCommandQueue( + &d3D12CommandQueueDesc, + FX.__uuidof(), + (void**)d3D12CommandQueue).Assert(); } - /// - /// 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) + // Create the direct fence + fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence) { - 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); + this.d3D12Device.Get()->CreateFence( + 0, + D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE, + FX.__uuidof(), + (void**)d3D12Fence).Assert(); } - /// - /// Presents the last rendered frame for the current application. - /// - private unsafe void OnPresent() + // Create the swap chain to display frames + using (ComPtr dxgiFactory2 = default) { - _ = FX.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, 1); + FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof(), (void**)dxgiFactory2.GetAddressOf()).Assert(); - using ComPtr d3D12Resource = default; + 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 = (uint)Math.Max(Math.Ceiling(this.width * this.compositionScaleX * this.targetResolutionScale), 1.0); + dxgiSwapChainDesc1.Height = (uint)Math.Max(Math.Ceiling(this.height * this.compositionScaleY * this.targetResolutionScale), 1.0); + 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 = FX.DXGI_USAGE_RENDER_TARGET_OUTPUT; - // Get the underlying ID3D12Resource pointer for the texture - InteropServices.TryGetID3D12Resource(this.texture!, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf()).Assert(); + using ComPtr dxgiSwapChain1 = default; - // Get the target back buffer to update - ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch + dxgiFactory2.Get()->CreateSwapChainForComposition( + (IUnknown*)this.d3D12CommandQueue.Get(), + &dxgiSwapChainDesc1, + null, + (IDXGISwapChain1**)&dxgiSwapChain1).Assert(); + + fixed (IDXGISwapChain2** dxgiSwapChain2 = this.dxgiSwapChain2) { - 0 => this.d3D12Resource0.Get(), - 1 => this.d3D12Resource1.Get(), - _ => null - }; + dxgiSwapChain1.CopyTo(dxgiSwapChain2).Assert(); + } + } - this.currentBufferIndex ^= 1; + // Get the awaitable object to synchronizize present calls + this.frameLatencyWaitableObject = this.dxgiSwapChain2.Get()->GetFrameLatencyWaitableObject(); - // Reset the command list and command allocator - this.d3D12CommandAllocator.Get()->Reset().Assert(); - this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null).Assert(); + // Create the command allocator to use + fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator) + { + this.d3D12Device.Get()->CreateCommandAllocator( + D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT, + FX.__uuidof(), + (void**)d3D12CommandAllocator).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) - }; + // 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, + null, + FX.__uuidof(), + (void**)d3D12GraphicsCommandList).Assert(); + } - // Transition the resources to COPY_DEST and COPY_SOURCE respectively - this.d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); + // Close the command list to prepare it for future use + this.d3D12GraphicsCommandList.Get()->Close().Assert(); - // Copy the generated frame to the target back buffer - this.d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get()); + // 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; - d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition( + 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(); + + using ComPtr idxgiSwapChain = default; + + this.dxgiSwapChain2.CopyTo(&idxgiSwapChain).Assert(); + + swapChainPanelNative.Get()->SetSwapChain(idxgiSwapChain.Get()).Assert(); + + 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(); + + // Wait for the fence again to ensure there are no pending operations + this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default).Assert(); + + this.nextD3D12FenceValue++; + + // Dispose the old buffers before resizing the buffer + this.d3D12Resource0.Dispose(); + this.d3D12Resource1.Dispose(); + + // Resize the swap chain buffers + this.dxgiSwapChain2.Get()->ResizeBuffers( + 2, + (uint)Math.Max(Math.Ceiling(this.width * this.compositionScaleX * this.targetResolutionScale), 1.0), + (uint)Math.Max(Math.Ceiling(this.height * this.compositionScaleY * this.targetResolutionScale), 1.0), + 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 / this.targetResolutionScale); + transformMatrix._22 = (1 / this.compositionScaleY) * (1 / this.targetResolutionScale); + + this.dxgiSwapChain2.Get()->SetMatrixTransform(&transformMatrix).Assert(); + + // Retrieve the back buffers for the swap chain + fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0) + fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1) + { + this.dxgiSwapChain2.Get()->GetBuffer(0, FX.__uuidof(), (void**)d3D12Resource0).Assert(); + this.dxgiSwapChain2.Get()->GetBuffer(1, FX.__uuidof(), (void**)d3D12Resource1).Assert(); + } + + // Get the index of the initial back buffer + using (ComPtr dxgiSwapChain3 = default) + { + this.dxgiSwapChain2.CopyTo(dxgiSwapChain3.GetAddressOf()).Assert(); + + this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex(); + } + + this.texture?.Dispose(); + + D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc(); + + // Create the 2D texture to use to generate frames to display + this.texture = Gpu.Default.AllocateReadWriteTexture2D( + (int)d3D12Resource0Description.Width, + (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) + { + 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() + { + _ = FX.WaitForSingleObjectEx(frameLatencyWaitableObject, 1000, 1); + + using ComPtr d3D12Resource = default; + + // Get the underlying ID3D12Resource pointer for the texture + InteropServices.TryGetID3D12Resource(this.texture!, FX.__uuidof(), (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_COPY_SOURCE, - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - - d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition( + 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_COPY_DEST, - D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON); + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST) + }; - // Transition the resources back to COMMON and UNORDERED_ACCESS respectively - this.d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); + // Transition the resources to COPY_DEST and COPY_SOURCE respectively + this.d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); - this.d3D12GraphicsCommandList.Get()->Close().Assert(); + // Copy the generated frame to the target back buffer + this.d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get()); - // 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(); + d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition( + d3D12Resource.Get(), + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - // Present the new frame - this.dxgiSwapChain2.Get()->Present(0, 0).Assert(); + d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition( + d3D12ResourceBackBuffer, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON); - if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) - { - this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default).Assert(); - } + // Transition the resources back to COMMON and UNORDERED_ACCESS respectively + this.d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers); - this.nextD3D12FenceValue++; + this.d3D12GraphicsCommandList.Get()->Close().Assert(); + + // 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(); + + // Present the new frame + this.dxgiSwapChain2.Get()->Present(0, 0).Assert(); + + if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue()) + { + this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default).Assert(); } - /// - /// Executes the render loop for the current panel. - /// - /// This method assumes to be invoked from a background thread. - private void OnStartRenderLoop() + this.nextD3D12FenceValue++; + } + + /// + /// Executes the render loop for the current panel. + /// + /// This method assumes to be invoked from a background thread. + private void OnStartRenderLoop() + { + static void ExecuteRenderLoop(ComputeShaderPanel @this) { - static void ExecuteRenderLoop(ComputeShaderPanel @this) + Stopwatch + renderStopwatch = @this.renderStopwatch ??= new(), + frameStopwatch = Stopwatch.StartNew(); + + DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + + 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) { - Stopwatch - renderStopwatch = @this.renderStopwatch ??= new(), - frameStopwatch = Stopwatch.StartNew(); + // Update the resolution mode, if needed + if (isDynamicResolutionEnabled != @this.isDynamicResolutionEnabled) + { + isDynamicResolutionEnabled = !isDynamicResolutionEnabled; - DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher); + if (isDynamicResolutionEnabled) + { + DynamicResolutionManager.Create(out frameTimeWatcher); + } + else + { + @this.targetResolutionScale = @this.resolutionScale; + } + } - bool isDynamicResolutionEnabled = @this.isDynamicResolutionEnabled; + // 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(); - // 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); + renderStopwatch.Stop(); } - /// - /// Stops the current render loop, if one is running. - /// - private void OnStopRenderLoop() + 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) { - this.isCancellationRequested = true; + renderThread.Join(); } - /// - /// 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.dxgiSwapChain2.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.dxgiSwapChain2.Dispose(); + this.d3D12Resource0.Dispose(); + this.d3D12Resource1.Dispose(); + this.texture?.Dispose(); } } diff --git a/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.cs b/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.cs index 6a8d241d..7ca0e51c 100644 --- a/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.cs +++ b/src/ComputeSharp.WinUI/Controls/ComputeShaderPanel.cs @@ -1,70 +1,69 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; -namespace ComputeSharp.WinUI +namespace ComputeSharp.WinUI; + +/// +/// A custom that can be used to render animated backgrounds. +/// It is powered by ComputeSharp and leverages compute shaders to create frames to display. +/// +public sealed unsafe partial class ComputeShaderPanel : SwapChainPanel { /// - /// A custom that can be used to render animated backgrounds. - /// It is powered by ComputeSharp and leverages compute shaders to create frames to display. + /// Creates a new instance. /// - public sealed unsafe partial class ComputeShaderPanel : SwapChainPanel + public ComputeShaderPanel() { - /// - /// Creates a new instance. - /// - public ComputeShaderPanel() - { - this.Loaded += ComputeShaderPanel_Loaded; - this.Unloaded += ComputeShaderPanel_Unloaded; - this.SizeChanged += ComputeShaderPanel_SizeChanged; - this.CompositionScaleChanged += ComputeShaderPanel_CompositionScaleChanged; - } + 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(); - } + /// + /// 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; + // 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; - OnInitialize(); - OnStartRenderLoop(); - } + OnInitialize(); + OnStartRenderLoop(); + } - // Requests a cancellation for the render thread - private void ComputeShaderPanel_Unloaded(object sender, RoutedEventArgs e) - { - OnStopRenderLoop(); - } + // Requests a cancellation for the render thread + private void ComputeShaderPanel_Unloaded(object sender, RoutedEventArgs e) + { + OnStopRenderLoop(); + } - // 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; + // 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(); - } + OnResize(); + } - // 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; + // 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(); - } + OnResize(); } } diff --git a/src/ComputeSharp.WinUI/Helpers/DynamicResolutionManager.cs b/src/ComputeSharp.WinUI/Helpers/DynamicResolutionManager.cs index 78d9dcdb..802650db 100644 --- a/src/ComputeSharp.WinUI/Helpers/DynamicResolutionManager.cs +++ b/src/ComputeSharp.WinUI/Helpers/DynamicResolutionManager.cs @@ -2,128 +2,127 @@ using System.Runtime.InteropServices; using System.Threading; -namespace ComputeSharp.WinUI.Helpers +namespace ComputeSharp.WinUI.Helpers; + +/// +/// A helper type that is responsible for applying dynamic resolution changes. +/// +internal unsafe ref struct DynamicResolutionManager { /// - /// A helper type that is responsible for applying dynamic resolution changes. + /// The target frame time in ticks to reach 60fps (set to 64fps). /// - internal unsafe ref struct DynamicResolutionManager + 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. + /// + private const int SlidingFrameTimeWindowLength = 32; + + /// + /// The threshold for scale factor updates. + /// + private const float ScaleFactorDeltaThreshold = 0.005f; + + /// + /// The constant multiplicative factor for the scale factor. + /// + private const float ScaleFactorDeltaK = 0.8f; + + /// + /// The window of registered frame times for previous frames. + /// + private fixed long frameTimesInTicks[SlidingFrameTimeWindowLength]; + + /// + /// The current index into . + /// + /// + /// This will have a value of -1 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. + /// + private int frameTimeOffset; + + /// + /// The current sum of values within . + /// + private long slidingFrameTimeWindowSum; + + /// + /// Initializes a new instance. + /// + /// The resulting instance. + public static void Create(out DynamicResolutionManager manager) { - /// - /// The target frame time in ticks to reach 60fps (set to 64fps). - /// - public const long TargetFrameTimeInTicksFor60fps = 156250; + manager.frameTimeOffset = 0; + manager.slidingFrameTimeWindowSum = TargetFrameTimeInTicksFor60fps * SlidingFrameTimeWindowLength; - /// - /// The upper frame time threshold in ticks to reach 60fps. - /// - private const long UpperFrameTimeThresholdInTicksFor60fps = 166666; + MemoryMarshal.CreateSpan(ref manager.frameTimesInTicks[0], SlidingFrameTimeWindowLength).Fill(TargetFrameTimeInTicksFor60fps); + } - /// - /// 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. - /// - private const int SlidingFrameTimeWindowLength = 32; - - /// - /// The threshold for scale factor updates. - /// - private const float ScaleFactorDeltaThreshold = 0.005f; - - /// - /// The constant multiplicative factor for the scale factor. - /// - private const float ScaleFactorDeltaK = 0.8f; - - /// - /// The window of registered frame times for previous frames. - /// - private fixed long frameTimesInTicks[SlidingFrameTimeWindowLength]; - - /// - /// The current index into . - /// - /// - /// This will have a value of -1 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. - /// - private int frameTimeOffset; - - /// - /// The current sum of values within . - /// - private long slidingFrameTimeWindowSum; - - /// - /// Initializes a new instance. - /// - /// The resulting instance. - public static void Create(out DynamicResolutionManager manager) + /// + /// Advances one frame and updates the scale factor, if needed. + /// + /// The frame time in ticks for the last rendered frame. + /// The current scale factor value being used to render frames. + /// Whether or not has been updated and a resize is needed. + public bool Advance(long frameTimeInTicks, ref float scaleFactor) + { + // Ignore the current frame if a resize has just happened + if (this.frameTimeOffset == -1) { - manager.frameTimeOffset = 0; - manager.slidingFrameTimeWindowSum = TargetFrameTimeInTicksFor60fps * SlidingFrameTimeWindowLength; - - MemoryMarshal.CreateSpan(ref manager.frameTimesInTicks[0], SlidingFrameTimeWindowLength).Fill(TargetFrameTimeInTicksFor60fps); - } - - /// - /// Advances one frame and updates the scale factor, if needed. - /// - /// The frame time in ticks for the last rendered frame. - /// The current scale factor value being used to render frames. - /// Whether or not has been updated and a resize is needed. - 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 is < LowerFrameTimeThresholdInTicksFor60fps or > UpperFrameTimeThresholdInTicksFor60fps) - { - float - frameTimeDelta = (TargetFrameTimeInTicksFor60fps - averageFrameTimeInTicks) / (float)averageFrameTimeInTicks, - scaleFactorDelta = scaleFactor * frameTimeDelta * ScaleFactorDeltaK, - 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; - } - } - } + 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 is < LowerFrameTimeThresholdInTicksFor60fps or > UpperFrameTimeThresholdInTicksFor60fps) + { + float + frameTimeDelta = (TargetFrameTimeInTicksFor60fps - averageFrameTimeInTicks) / (float)averageFrameTimeInTicks, + scaleFactorDelta = scaleFactor * frameTimeDelta * ScaleFactorDeltaK, + 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; } } diff --git a/src/ComputeSharp.WinUI/IShaderRunner.cs b/src/ComputeSharp.WinUI/IShaderRunner.cs index ed633df9..8a1deb5e 100644 --- a/src/ComputeSharp.WinUI/IShaderRunner.cs +++ b/src/ComputeSharp.WinUI/IShaderRunner.cs @@ -1,17 +1,16 @@ using System; -namespace ComputeSharp.WinUI +namespace ComputeSharp.WinUI; + +/// +/// An interface for a shader runner to be used with . +/// +public interface IShaderRunner { /// - /// An interface for a shader runner to be used with . + /// Renders a single frame to a texture. /// - public interface IShaderRunner - { - /// - /// Renders a single frame to a texture. - /// - /// The target texture to render the frame to. - /// The timespan for the current frame. - public void Execute(IReadWriteTexture2D texture, TimeSpan timespan); - } + /// The target texture to render the frame to. + /// The timespan for the current frame. + public void Execute(IReadWriteTexture2D texture, TimeSpan timespan); } diff --git a/src/ComputeSharp.WinUI/ShaderRunner{T}.cs b/src/ComputeSharp.WinUI/ShaderRunner{T}.cs index c51232ff..af32f397 100644 --- a/src/ComputeSharp.WinUI/ShaderRunner{T}.cs +++ b/src/ComputeSharp.WinUI/ShaderRunner{T}.cs @@ -1,42 +1,41 @@ using System; -namespace ComputeSharp.WinUI +namespace ComputeSharp.WinUI; + +/// +/// An implementation powered by a supplied shader type. +/// +/// The type of shader to use to render frames. +public sealed class ShaderRunner : IShaderRunner + where T : struct, IPixelShader { /// - /// An implementation powered by a supplied shader type. + /// The instance used to create shaders to run. /// - /// The type of shader to use to render frames. - public sealed class ShaderRunner : IShaderRunner - where T : struct, IPixelShader + private readonly Func shaderFactory; + + /// + /// Creates a new 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. + /// + public ShaderRunner() { - /// - /// The instance used to create shaders to run. - /// - private readonly Func shaderFactory; + this.shaderFactory = static _ => default; + } - /// - /// Creates a new 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. - /// - public ShaderRunner() - { - this.shaderFactory = static _ => default; - } + /// + /// Creates a new instance. + /// + /// The instance used to create shaders to run. + public ShaderRunner(Func shaderFactory) + { + this.shaderFactory = shaderFactory; + } - /// - /// Creates a new instance. - /// - /// The instance used to create shaders to run. - public ShaderRunner(Func shaderFactory) - { - this.shaderFactory = shaderFactory; - } - - /// - public void Execute(IReadWriteTexture2D texture, TimeSpan time) - { - Gpu.Default.ForEach(texture, this.shaderFactory(time)); - } + /// + public void Execute(IReadWriteTexture2D texture, TimeSpan time) + { + Gpu.Default.ForEach(texture, this.shaderFactory(time)); } }