using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
#if WINDOWS_UWP
using ComputeSharp.Uwp.Extensions;
#else
using ComputeSharp.WinUI.Extensions;
#endif
using Microsoft.Toolkit.Diagnostics;
#pragma warning disable CS0420
#if WINDOWS_UWP
namespace ComputeSharp.Uwp.Helpers;
#else
namespace ComputeSharp.WinUI.Helpers;
#endif
///
partial class SwapChainManager
{
///
/// Starts the current render loop.
///
/// The instance to use, if available.
/// The instance to use to render frames.
public async void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner)
{
ThrowIfDisposed();
Guard.IsNotNull(shaderRunner, nameof(shaderRunner));
using (await this.setupSemaphore.LockAsync())
{
this.renderCancellationTokenSource?.Cancel();
await this.renderSemaphore.WaitAsync();
Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop());
this.frameRequestQueue = frameRequestQueue;
this.shaderRunner = shaderRunner;
this.renderCancellationTokenSource = new CancellationTokenSource();
this.renderThread = newRenderThread;
this.renderSemaphore = new SemaphoreSlim(0, 1);
this.isResizePending = true;
newRenderThread.Start(this);
}
}
///
/// Stops the current render loop, if one is running.
///
public async void StopRenderLoop()
{
ThrowIfDisposed();
using (await this.setupSemaphore.LockAsync())
{
this.renderCancellationTokenSource?.Cancel();
}
}
///
/// Queues a change in the dynamic resolution mode.
///
/// Whether or not to use dynamic resolution.
public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled)
{
ThrowIfDisposed();
using (await this.setupSemaphore.LockAsync())
{
// If there is a render thread currently running, stop it and restart it
if (this.renderCancellationTokenSource?.IsCancellationRequested == false)
{
this.renderCancellationTokenSource?.Cancel();
await this.renderSemaphore.WaitAsync();
Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop());
this.renderCancellationTokenSource = new CancellationTokenSource();
this.renderThread = newRenderThread;
this.renderSemaphore = new SemaphoreSlim(0, 1);
this.isDynamicResolutionEnabled = isDynamicResolutionEnabled;
this.isResizePending = true;
newRenderThread.Start(this);
}
else
{
this.isDynamicResolutionEnabled = isDynamicResolutionEnabled;
}
}
}
///
/// Queues a resize operation.
///
/// The width of the render resolution.
/// The height of the render resolution.
public void QueueResize(double width, double height)
{
ThrowIfDisposed();
this.width = (float)width;
this.height = (float)height;
this.isResizePending = true;
}
///
/// Queues a change in the composition scale factors.
///
/// The composition scale on the X axis.
/// The composition scale on the Y axis
public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY)
{
ThrowIfDisposed();
this.compositionScaleX = (float)compositionScaleX;
this.compositionScaleY = (float)compositionScaleY;
this.isResizePending = true;
}
///
/// Queues a change in the resolution scale factor.
///
/// The resolution scale factor to use.
public void QueueResolutionScaleChange(double resolutionScale)
{
ThrowIfDisposed();
this.resolutionScale = (float)resolutionScale;
this.isResizePending = true;
}
///
/// Selects the right render loop to start.
///
private void SwitchAndStartRenderLoop()
{
try
{
OnRenderingStarted();
if (this.isDynamicResolutionEnabled)
{
this.dynamicResolutionScale = this.resolutionScale;
RenderLoopWithDynamicResolution();
}
else
{
RenderLoop();
}
OnRenderingStopped();
}
catch (Exception e)
{
OnRenderingFailed(e);
}
finally
{
this.renderSemaphore.Release();
}
}
///
/// The core render loop.
///
[MethodImpl(MethodImplOptions.NoInlining)]
private void RenderLoop()
{
Stopwatch renderStopwatch = this.renderStopwatch ??= new();
CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token;
if (!OnFrameRequest(out object? parameter, cancellationToken))
{
return;
}
OnResize();
// Start the initial frame separately, before the timer starts. This ensures that
// resuming after a pause correctly renders the first frame at the right time.
if (OnUpdate(renderStopwatch.Elapsed, parameter))
{
OnPresent();
}
renderStopwatch.Start();
// Main render loop, until cancellation is requested
while (!cancellationToken.IsCancellationRequested)
{
if (!OnFrameRequest(out parameter, cancellationToken))
{
return;
}
OnResize();
if (OnUpdate(renderStopwatch.Elapsed, parameter))
{
OnPresent();
}
}
renderStopwatch.Stop();
}
///
/// The core render loop with dynamic resolution.
///
[MethodImpl(MethodImplOptions.NoInlining)]
private void RenderLoopWithDynamicResolution()
{
Stopwatch renderStopwatch = this.renderStopwatch ??= new();
Stopwatch frameStopwatch = new();
CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token;
DynamicResolutionManager.Create(out DynamicResolutionManager frameTimeWatcher);
if (!OnFrameRequest(out object? parameter, cancellationToken))
{
return;
}
OnResize();
if (OnUpdate(renderStopwatch.Elapsed, parameter))
{
OnPresent();
}
renderStopwatch.Start();
while (!cancellationToken.IsCancellationRequested)
{
if (!OnFrameRequest(out parameter, cancellationToken))
{
return;
}
OnResize();
frameStopwatch.Restart();
if (OnUpdate(renderStopwatch.Elapsed, parameter))
{
OnPresent();
// Evaluate the dynamic resolution frame time step
if (frameTimeWatcher.Advance(frameStopwatch.ElapsedTicks, ref this.dynamicResolutionScale))
{
this.isResizePending = true;
}
}
}
renderStopwatch.Stop();
}
///
/// Waits for a new frame request and retrieves its parameter.
///
/// The input parameter for the frame to render.
/// A token to cancel waiting for a new frame.
/// Whether the operation was canceled.
private bool OnFrameRequest(out object? parameter, CancellationToken token)
{
if (this.frameRequestQueue is IFrameRequestQueue frameRequestQueue)
{
[MethodImpl(MethodImplOptions.NoInlining)]
static bool WaitForFrameRequest(IFrameRequestQueue frameRequestQueue, out object? parameter, CancellationToken token)
{
try
{
// Wait for a new frame request
frameRequestQueue.Dequeue(out parameter, token);
return true;
}
catch (OperationCanceledException)
{
parameter = null;
return false;
}
}
return WaitForFrameRequest(frameRequestQueue, out parameter, token);
}
parameter = null;
return true;
}
///
/// Resizes the current application, if needed.
///
private void OnResize()
{
if (this.isResizePending)
{
ApplyResize();
this.isResizePending = false;
}
}
///
/// Updates the render resolution, if needed, and renders a new frame.
///
/// The current time since the start of the application.
/// The input parameter for the frame being rendered.
/// Whether or not to present the resulting frame.
private bool OnUpdate(TimeSpan time, object? parameter)
{
return this.shaderRunner!.TryExecute(this.texture!, time, parameter);
}
///
/// Presents the last rendered frame for the current application.
///
private unsafe partial void OnPresent();
///
/// Raises .
///
private void OnRenderingStarted()
{
_ = this.dispatcherQueue.TryEnqueue(() => RenderingStarted?.Invoke(this.owner, EventArgs.Empty));
}
///
/// Raises .
///
private void OnRenderingStopped()
{
_ = this.dispatcherQueue.TryEnqueue(() => RenderingStopped?.Invoke(this.owner, EventArgs.Empty));
}
///
/// Raises .
///
/// The being thrown that caused rendering to stop.
private void OnRenderingFailed(Exception e)
{
_ = this.dispatcherQueue.TryEnqueue(() => RenderingFailed?.Invoke(this.owner, e));
}
///
/// Stops the current render loop, if one is running, and waits for it.
///
/// This method doesn't check for disposal.
private void UnsafeStopRenderLoopAndWait()
{
ThrowIfDisposed();
this.setupSemaphore.Wait();
this.renderCancellationTokenSource?.Cancel();
this.renderSemaphore.Wait();
}
}