Skip to content

feat(skia): Render-loop FrameTick simplification - #23047

Merged
MartinZikmund merged 2 commits into
dev/mazi/win32renderfrom
dev/mazi/render-loop-core
May 6, 2026
Merged

MartinZikmund merged 2 commits into
dev/mazi/win32renderfrom
dev/mazi/render-loop-core

Conversation

@MartinZikmund

@MartinZikmund MartinZikmund commented Apr 14, 2026 •

Copy link
Copy Markdown
Member

Summary

This is the second PR in a 2-PR split from the original dev/mazi/render-loop-core work. Base branch is dev/mazi/win32render (the Win32 vsync + render thread foundation); merge that PR first.

Replaces the legacy Skia render scheduler (two-phase OnNativePlatformFrameRequested + EnqueueRender + OnRenderFrameOpportunity) with a single batched FrameTick per scheduling round, plus the cross-platform throttle/present-completion contract that lets the Win32 render thread (introduced in the base PR) fully participate in pacing and FrameRendered notification.

Cross-platform (Uno.UI)

  • CompositionTarget.RenderScheduling.skia.cs: new ScheduleFrameTick / FrameTick / OnFrameConsumed / OnFramePresented, _waitingForPresent throttle that pipelines render-side work with the host's present, reentrancy guard with ReentrantFrameTickCount diagnostic, and SynchronousRender(forceLayout) for hosts that need an out-of-tick record (Win32 modal pumps).
  • CompositionTarget.Rendering.skia.cs: OnFrameConsumed clears the throttle when Draw borrows the recorded SKPicture; FrameRendered moves to OnFramePresented; InvokeRendering accepts a TimeSpan so future hosts can pass a vsync-aligned timestamp.
  • IXamlRootHost.SupportsRenderThrottle: opt-in for hosts that signal present completion themselves (Win32). False-by-default keeps WASM/X11/macOS on the auto-OnFramePresented path inside OnNativePlatformFrameRequested.
  • CoreServices.cs: defer request-additional-frame to ScheduleFrameTick on __SKIA__; non-Skia keeps the layout-only path.
  • BaseWindowImplementation.NotifyContentLoaded defers TryActivate via the dispatcher to avoid frame-tick re-entry from Loaded handlers.

Win32 wiring (on top of the new vsync + render thread foundation)

  • Win32WindowWrapper.SupportsRenderThrottle => true; the render thread routes its present-ack through CompositionTarget.OnFramePresented at NativeDispatcherPriority.High.
  • RenderThread only signals presented when an actual frame was drawn and copied (skips phantom WM_PAINT before first record).
  • WM_SIZE / WM_NCPAINT / WM_MOVE: SynchronousRender(forceLayout: true) keeps visuals fresh during modal pumps when the dispatcher is paused; ShowCore drives a full FrameTick + bounded WaitForNextPresent so the first painted frame reflects post-Loaded state.

Dispatcher (Uno.UI.Dispatching)

  • NativeDispatcher: drop _compositionTargets / TryGetRenderAction / EnqueueRender — the new FrameTick posts ordinary Normal-priority items.

Tests

  • WindowHelper.WaitForIdle aligned with the new FrameTick scheduling: wait for layout/Loaded to settle on idle, time out the wait-for-opened path to surface hangs, avoid leaks across runs.
  • Given_ComboBox: skip the popup-dismiss test on NativeWinUI where dismissal timing diverges from Skia render-loop pacing.
  • Given_ItemsRepeater: minor tolerance for the new batching cadence.

Test plan

  • Merge base PR (dev/mazi/win32render) first, then this PR rebases on master cleanly.
  • dotnet build src/Uno.UI-Skia-only.slnf -p:RunAnalyzersDuringBuild=false succeeds.
  • SamplesApp.Skia.Generic on Win32 launches, no visual regressions, FPS stable at refresh rate, FrameRendered fires post-present.
  • SamplesApp.Skia on macOS / Linux X11 still renders (default path, throttle disabled).
  • Given_ItemsRepeater runtime tests pass on Skia Desktop.
  • WindowHelper.WaitForIdle settles within wall-clock expectations (no spin, no hang on first-frame opened-event timeout).
  • CompositionTarget.ReentrantFrameTickCount stays at 0 in normal scenarios.

🤖 Generated with Claude Code

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the Skia rendering pipeline to use a single batched FrameTick on the UI thread (layout → loaded events → CompositionTarget.Rendering → render) and introduces Win32 render-thread presentation/throttling, along with plumbing on IXamlRootHost for frame VSync timestamps.

Changes:

  • Restructures Skia render scheduling around a dispatcher-posted FrameTick, and moves CompositionTarget.Rendering firing into that tick with a VSync-aware timestamp input.
  • Adds a Win32 dedicated render thread that owns Draw + CopyPixels (SwapBuffers/BitBlt), with UI-thread recording and host-level throttling via OnFramePresented.
  • Extends dispatcher priorities with an internal Render priority and updates additional-frame scheduling to align with it.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/Uno.UI/UI/Xaml/Window/Implementations/BaseWindowImplementation.cs Defers window activation to avoid re-entrant frame tick during loaded processing.
src/Uno.UI/UI/Xaml/Media/CompositionTarget.Rendering.skia.cs Changes Rendering event firing to be explicitly UI-thread-only and VSync-time driven.
src/Uno.UI/UI/Xaml/Media/CompositionTarget.RenderScheduling.skia.cs Implements the new batched FrameTick, render throttling, and re-entrancy handling.
src/Uno.UI/UI/Xaml/Internal/CoreServices.cs Routes Skia “additional frame” ticks to CompositionTarget.ScheduleFrameTick() at Render priority.
src/Uno.UI/Hosting/IXamlRootHost.cs Adds SupportsRenderThrottle and FrameVsyncTimestamp defaults for platform hosts.
src/Uno.UI.Runtime.Skia.Win32/UI/Xaml/Window/Win32WindowWrapper.cs Switches Win32 message handling to sync-record + render-thread presentation signaling.
src/Uno.UI.Runtime.Skia.Win32/Rendering/Win32WindowWrapper.Rendering.cs Moves presentation to render thread; updates invalidate behavior and presentation callbacks.
src/Uno.UI.Runtime.Skia.Win32/Rendering/Win32WindowWrapper.Rendering.Software.cs Adds DwmFlush() pacing for software renderer VSync alignment.
src/Uno.UI.Runtime.Skia.Win32/Rendering/Win32WindowWrapper.Rendering.OpenGl.cs Explicitly sets OpenGL swap interval via wglSwapIntervalEXT when available.
src/Uno.UI.Runtime.Skia.Win32/Rendering/Win32WindowWrapper.RenderThread.cs Introduces the dedicated Win32 render thread implementation.
src/Uno.UI.Runtime.Skia.Win32/Graphics/Display/Win32WindowWrapper.DisplayInformation.cs Removes frame pacer refresh-rate updates (refresh rate remains tracked for display info).
src/Uno.UI.Runtime.Skia.Win32.Support/NativeMethods.txt Adds DwmFlush P/Invoke surface.
src/Uno.UI.Dispatching/Native/NativeDispatcherPriority.cs Adds internal Render priority and shifts Low/Idle ordering.
src/Uno.UI.Dispatching/Native/NativeDispatcher.cs Expands queues to include Render priority and removes the prior composition-target render injection mechanism.
src/Uno.UI.Dispatching/Dispatching/DispatcherQueue.cs Updates DispatcherQueuePriority → NativeDispatcherPriority mapping to avoid relying on enum numeric layout.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 207300 has failed on Uno.UI - CI.

Copilot AI review requested due to automatic review settings April 19, 2026 09:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 4 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/Uno.UI/Hosting/IXamlRootHost.cs Resolved
@MartinZikmund
MartinZikmund marked this pull request as ready for review April 19, 2026 09:23
@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 208018 has failed on Uno.UI - CI.

Copilot AI review requested due to automatic review settings April 19, 2026 13:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 9 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/Uno.UI/Hosting/IXamlRootHost.cs Resolved
Copilot AI review requested due to automatic review settings April 19, 2026 15:47
@MartinZikmund
MartinZikmund force-pushed the dev/mazi/render-loop-core branch from 507ec57 to a3c31b7 Compare April 19, 2026 15:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 208026 has failed on Uno.UI - CI.

@MartinZikmund
MartinZikmund force-pushed the dev/mazi/render-loop-core branch from 5b7f12e to d95e9b0 Compare April 21, 2026 16:33
Copilot AI review requested due to automatic review settings April 21, 2026 18:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 208427 did not find any UI Test snapshots differences.

@MartinZikmund
MartinZikmund force-pushed the dev/mazi/render-loop-core branch from 7723801 to c887d16 Compare April 22, 2026 10:51
Copilot AI review requested due to automatic review settings April 22, 2026 13:20
@unodevops

Copy link
Copy Markdown
Contributor

1 similar comment
@unodevops

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 4 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +105 to +127
// 250 ms covers a present (~16 ms at 60 Hz) plus slack. If that fails, the GPU
// is likely hung. Wait one more bounded interval (2 s) and then abandon: leaving
// the render thread (background, marked at construction) blocked is preferable
// to hanging the UI thread on window close. The leaked synchronization
// primitives and renderer outlive the thread, so the OS reclaims them at exit.
var joined = _thread.Join(timeout: TimeSpan.FromMilliseconds(250));
if (!joined)
{
typeof(RenderThread).LogWarn()?.Warn(
"Render thread did not exit within 250 ms during dispose; waiting up to 2 s more " +
"before abandoning. This usually indicates a stuck GPU present " +
"(SwapBuffers/BitBlt/DwmFlush blocked).");

joined = _thread.Join(timeout: TimeSpan.FromSeconds(2));
if (!joined)
{
typeof(RenderThread).LogError()?.Error(
"Render thread still alive after 2 s; abandoning to keep window close responsive. " +
"Leaking _frameSignal, _presentedEvent and renderer until process exit.");
return;
}
}

Comment on lines +491 to 499
_renderThread?.Dispose();
_renderThread = null;
// Dispose the cached SKSurface before the renderer: on Vulkan it references
// GPU resources owned by _renderer (see Win32WindowWrapper.Rendering.Vulkan.cs)
// and the render thread has already been joined, so no background access remains.
_surface?.Dispose();
_surface = null;
_renderer.Dispose();
_rendererDisposed = true;
Comment on lines +18 to +38
/// <summary>
/// True if the host has its own present-completion signal (e.g. a dedicated render
/// thread that posts back to the UI thread after SwapBuffers/BitBlt). Such hosts call
/// CompositionTarget.OnFramePresented themselves at the right moment.
///
/// When false (the default), CompositionTarget auto-calls OnFramePresented from inside
/// OnNativePlatformFrameRequested after Draw — that's the platform's vsync callback
/// (Choreographer on Android, requestAnimationFrame on WASM, etc.) and is the natural
/// "previous frame is on its way to the display" moment for hosts that don't need
/// post-present accuracy.
///
/// Either way, <c>_waitingForPresent</c> paces render-side work while the previous
/// frame is still in flight: frame ticks may still be enqueued (so layout and Loaded
/// events keep flowing), but the Rendering event and Render call inside FrameTick
/// are gated until the prior frame is consumed by the render path. That gate is
/// cleared by <c>OnFrameConsumed()</c> at <c>Draw</c> entry; <c>OnFramePresented</c>
/// is only used for post-present bookkeeping (FrameRendered/FPS).
///
/// Currently only Win32 returns true (its render thread is the present signal).
/// </summary>
bool SupportsRenderThrottle => false;
Comment on lines +237 to +250
var tcs = new TaskCompletionSource<object>();
Microsoft.UI.Dispatching.DispatcherQueueTimer timer = null;
global::Windows.Foundation.TypedEventHandler<Microsoft.UI.Dispatching.DispatcherQueueTimer, object> handler = null;

await RootElementDispatcher.RunAsync(() =>
{
timer = dispatcherQueue.CreateTimer();
timer.Interval = TimeSpan.Zero;
timer.IsRepeating = false;
handler = (t, _) =>
{
t.Tick -= handler;
tcs.TrySetResult(null);
};
@unodevops

Copy link
Copy Markdown
Contributor

@nventive-devops

Copy link
Copy Markdown
Contributor

The build 209801 did not find any UI Test snapshots differences.

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 209801 has failed on Uno.UI - CI.

@MartinZikmund
MartinZikmund force-pushed the dev/mazi/render-loop-core branch from 49da334 to 14d77c9 Compare May 6, 2026 12:08
@unodevops

Copy link
Copy Markdown
Contributor

MartinZikmund and others added 2 commits May 6, 2026 14:48
…ring

Replace the legacy two-phase render scheduler (OnNativePlatformFrameRequested
+ EnqueueRender + OnRenderFrameOpportunity) with a single batched FrameTick
posted to the dispatcher per scheduling round. FrameTick sequences:
Layout -> Loaded events -> Layout -> Rendering -> Layout -> Render, and is
gated by an internal _waitingForPresent throttle that pipelines render-side
work with the host's present.

Cross-platform (Uno.UI):
 - CompositionTarget.RenderScheduling.skia.cs: ScheduleFrameTick / FrameTick
   / OnFrameConsumed / OnFramePresented; reentrancy guard with
   ReentrantFrameTickCount diagnostic; SynchronousRender helper for hosts
   that need an out-of-tick record (Win32 modal pumps).
 - CompositionTarget.Rendering.skia.cs: OnFrameConsumed clears the throttle
   when Draw borrows the recorded SKPicture; FrameRendered moves to
   OnFramePresented; InvokeRendering accepts a TimeSpan so future hosts can
   pass a vsync-aligned timestamp.
 - IXamlRootHost.SupportsRenderThrottle: opt-in for hosts that signal
   present completion themselves (Win32). False-by-default keeps WASM/X11
   on the auto-OnFramePresented path inside OnNativePlatformFrameRequested.
 - CoreServices.cs: defer request-additional-frame to ScheduleFrameTick on
   __SKIA__; non-Skia keeps the layout-only path.
 - BaseWindowImplementation.NotifyContentLoaded defers TryActivate via the
   dispatcher to avoid frame-tick re-entry from Loaded handlers.
 - SkiaRenderHelper FPS bookkeeping aligned with the new pre/post-present
   hooks.

Win32 wiring:
 - SupportsRenderThrottle => true; render thread routes its present-ack
   through CompositionTarget.OnFramePresented (NativeDispatcher.High) so
   throttle pacing and FrameRendered fire at real present time.
 - RenderThread only signals presented when an actual frame was drawn and
   copied (skips phantom WM_PAINT-before-first-record).
 - WM_SIZE / WM_NCPAINT / WM_MOVE: SynchronousRender(forceLayout: true)
   to keep visuals fresh during modal pumps when the dispatcher is paused;
   ShowCore drives a full FrameTick + bounded WaitForNextPresent so the
   first painted frame reflects post-Loaded state.

Dispatcher (Uno.UI.Dispatching):
 - NativeDispatcher: drop _compositionTargets / TryGetRenderAction /
   EnqueueRender — the new FrameTick posts ordinary Normal-priority items.
 - NativeDispatcherPriority: BOM cleanup.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
WindowHelper.WaitForIdle: align with the new FrameTick scheduling — wait
for layout/Loaded to settle on idle, time out the wait-for-opened path
to surface hangs instead of stalling indefinitely, and avoid leaking
helpers across runs.

Given_ComboBox: skip the popup-dismiss test on NativeWinUI where the
dismissal timing diverges from the Skia render-loop pacing.

Given_ItemsRepeater: minor tolerance adjustments for the new FrameTick
batching cadence.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 6, 2026 12:51
@MartinZikmund
MartinZikmund force-pushed the dev/mazi/render-loop-core branch from 14d77c9 to 068ea10 Compare May 6, 2026 12:51
@MartinZikmund MartinZikmund changed the title feat(skia): Rework render loop with Win32 render thread and VSync plumbing feat(skia): Render-loop FrameTick simplification May 6, 2026
@MartinZikmund
MartinZikmund changed the base branch from master to dev/mazi/win32render May 6, 2026 12:52
@MartinZikmund
MartinZikmund merged commit 1b214a8 into dev/mazi/win32render May 6, 2026
13 of 17 checks passed
@MartinZikmund
MartinZikmund deleted the dev/mazi/render-loop-core branch May 6, 2026 12:52
@MartinZikmund
MartinZikmund restored the dev/mazi/render-loop-core branch May 6, 2026 12:57

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.

return;
}

var tcs = new TaskCompletionSource<object>();
Comment on lines +18 to +22
/// <summary>
/// True if the host has its own present-completion signal (e.g. a dedicated render
/// thread that posts back to the UI thread after SwapBuffers/BitBlt). Such hosts call
/// CompositionTarget.OnFramePresented themselves at the right moment.
///
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/skia ✏️ Categorizes an issue or PR as relevant to Skia kind/documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants