|
| 1 | +// Copyright (c) Six Labors. |
| 2 | +// Licensed under the Six Labors Split License. |
| 3 | + |
| 4 | +using System.Diagnostics; |
| 5 | +using System.Runtime.InteropServices; |
| 6 | +using SixLabors.ImageSharp.Drawing.Processing; |
| 7 | +using SixLabors.ImageSharp.Drawing.Processing.Backends; |
| 8 | +using SixLabors.ImageSharp.PixelFormats; |
| 9 | + |
| 10 | +namespace WebGPUHostedWindowDemo.Controls; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// A reusable WinForms control that embeds a <see cref="WebGPUHostedWindow{TPixel}"/> and drives a continuous |
| 14 | +/// render loop via <see cref="Application.Idle"/>. Callers hook <see cref="PaintFrame"/> with their scene logic; |
| 15 | +/// the control handles construction, resize, acquire/present, and teardown. |
| 16 | +/// </summary> |
| 17 | +public sealed partial class WebGPURenderControl : Control |
| 18 | +{ |
| 19 | + private const int WM_MOVING = 0x0216; |
| 20 | + private const int WM_EXITSIZEMOVE = 0x0232; |
| 21 | + |
| 22 | + private WebGPUHostedWindow<Bgra32>? window; |
| 23 | + private bool idleHooked; |
| 24 | + private long lastTicks; |
| 25 | + private System.Windows.Forms.Timer? titleBarMoveTimer; |
| 26 | + private TitleBarListener? titleBarListener; |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Initializes a new instance of the <see cref="WebGPURenderControl"/> class. |
| 30 | + /// </summary> |
| 31 | + public WebGPURenderControl() |
| 32 | + { |
| 33 | + this.SetStyle( |
| 34 | + ControlStyles.AllPaintingInWmPaint | |
| 35 | + ControlStyles.Opaque | |
| 36 | + ControlStyles.UserPaint, |
| 37 | + true); |
| 38 | + |
| 39 | + this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false); |
| 40 | + } |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Raised each frame once the hosted window has acquired a drawable frame. |
| 44 | + /// </summary> |
| 45 | + public event Action<DrawingCanvas<Bgra32>, TimeSpan>? PaintFrame; |
| 46 | + |
| 47 | + /// <inheritdoc /> |
| 48 | + protected override void OnHandleCreated(EventArgs e) |
| 49 | + { |
| 50 | + base.OnHandleCreated(e); |
| 51 | + |
| 52 | + int width = Math.Max(this.ClientSize.Width, 1); |
| 53 | + int height = Math.Max(this.ClientSize.Height, 1); |
| 54 | + |
| 55 | + this.window = new WebGPUHostedWindow<Bgra32>( |
| 56 | + WebGPUWindowHost.Win32( |
| 57 | + this.Handle, |
| 58 | + Marshal.GetHINSTANCE(typeof(WebGPURenderControl).Module)), |
| 59 | + width, |
| 60 | + height); |
| 61 | + |
| 62 | + this.lastTicks = Stopwatch.GetTimestamp(); |
| 63 | + Application.Idle += this.OnApplicationIdle; |
| 64 | + this.idleHooked = true; |
| 65 | + |
| 66 | + // Application.Idle stops firing during a title-bar drag (modal move loop). |
| 67 | + // Attach a NativeWindow to the parent form's handle so we can see WM_MOVING |
| 68 | + // — which fires only during title-bar drags, never during border resizes — |
| 69 | + // and drive a short Timer during those. Border resize is left untouched. |
| 70 | + Form? parentForm = this.FindForm(); |
| 71 | + if (parentForm is not null && parentForm.IsHandleCreated) |
| 72 | + { |
| 73 | + this.titleBarMoveTimer = new System.Windows.Forms.Timer { Interval = 16 }; |
| 74 | + this.titleBarMoveTimer.Tick += this.OnTitleBarMoveTick; |
| 75 | + this.titleBarListener = new TitleBarListener(this); |
| 76 | + this.titleBarListener.AssignHandle(parentForm.Handle); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + /// <inheritdoc /> |
| 81 | + protected override void OnHandleDestroyed(EventArgs e) |
| 82 | + { |
| 83 | + if (this.idleHooked) |
| 84 | + { |
| 85 | + Application.Idle -= this.OnApplicationIdle; |
| 86 | + this.idleHooked = false; |
| 87 | + } |
| 88 | + |
| 89 | + this.titleBarListener?.ReleaseHandle(); |
| 90 | + this.titleBarListener = null; |
| 91 | + |
| 92 | + if (this.titleBarMoveTimer is not null) |
| 93 | + { |
| 94 | + this.titleBarMoveTimer.Stop(); |
| 95 | + this.titleBarMoveTimer.Tick -= this.OnTitleBarMoveTick; |
| 96 | + this.titleBarMoveTimer.Dispose(); |
| 97 | + this.titleBarMoveTimer = null; |
| 98 | + } |
| 99 | + |
| 100 | + this.window?.Dispose(); |
| 101 | + this.window = null; |
| 102 | + base.OnHandleDestroyed(e); |
| 103 | + } |
| 104 | + |
| 105 | + /// <inheritdoc /> |
| 106 | + protected override void OnResize(EventArgs e) |
| 107 | + { |
| 108 | + base.OnResize(e); |
| 109 | + if (this.window is not null && this.ClientSize.Width > 0 && this.ClientSize.Height > 0) |
| 110 | + { |
| 111 | + this.window.Resize(this.ClientSize.Width, this.ClientSize.Height); |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + /// <inheritdoc /> |
| 116 | + protected override void OnPaintBackground(PaintEventArgs pevent) |
| 117 | + { |
| 118 | + // WebGPU owns the surface; suppress the WinForms background paint. |
| 119 | + } |
| 120 | + |
| 121 | + /// <inheritdoc /> |
| 122 | + protected override void OnPaint(PaintEventArgs e) => this.RenderOnce(); |
| 123 | + |
| 124 | + // Application.Idle fires once when the WinForms message queue drains. Rendering only once |
| 125 | + // would leave the scene frozen between user input events, so we loop here — re-rendering as |
| 126 | + // long as the queue stays empty — and exit the moment a message arrives so WinForms can |
| 127 | + // process it. Frame pacing is delegated to the swap-chain present mode: with Fifo (v-sync) |
| 128 | + // TryAcquireFrame blocks until the display is ready, so this loop naturally runs at the |
| 129 | + // display's refresh rate without a software timer capping it. |
| 130 | + private void OnApplicationIdle(object? sender, EventArgs e) |
| 131 | + { |
| 132 | + while (IsApplicationIdle()) |
| 133 | + { |
| 134 | + this.RenderOnce(); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + private void OnTitleBarMoveTick(object? sender, EventArgs e) => this.RenderOnce(); |
| 139 | + |
| 140 | + // Hooks the parent form's handle so the control can observe WM_MOVING / WM_EXITSIZEMOVE |
| 141 | + // without requiring the form to know this control exists. |
| 142 | + private sealed class TitleBarListener(WebGPURenderControl owner) : NativeWindow |
| 143 | + { |
| 144 | + protected override void WndProc(ref Message m) |
| 145 | + { |
| 146 | + switch (m.Msg) |
| 147 | + { |
| 148 | + case WM_MOVING: |
| 149 | + owner.titleBarMoveTimer?.Start(); |
| 150 | + break; |
| 151 | + case WM_EXITSIZEMOVE: |
| 152 | + owner.titleBarMoveTimer?.Stop(); |
| 153 | + break; |
| 154 | + } |
| 155 | + |
| 156 | + base.WndProc(ref m); |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + private void RenderOnce() |
| 161 | + { |
| 162 | + if (this.window is null || this.ClientSize.Width <= 0 || this.ClientSize.Height <= 0) |
| 163 | + { |
| 164 | + return; |
| 165 | + } |
| 166 | + |
| 167 | + if (!this.window.TryAcquireFrame(out WebGPUWindowFrame<Bgra32>? frame)) |
| 168 | + { |
| 169 | + return; |
| 170 | + } |
| 171 | + |
| 172 | + long now = Stopwatch.GetTimestamp(); |
| 173 | + TimeSpan delta = TimeSpan.FromSeconds((now - this.lastTicks) / (double)Stopwatch.Frequency); |
| 174 | + this.lastTicks = now; |
| 175 | + |
| 176 | + using (frame) |
| 177 | + { |
| 178 | + this.PaintFrame?.Invoke(frame.Canvas, delta); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + // PeekMessage with wRemoveMsg = 0 (PM_NOREMOVE) asks the OS "is there a message waiting?" without |
| 183 | + // dequeuing it. Returning 0 means the queue is empty — the canonical "is the app idle right now" |
| 184 | + // check used by the WinForms continuous-render idiom. Cheaper than any managed alternative and the |
| 185 | + // only way to tell whether WinForms is about to break out of Application.Idle on the next pump. |
| 186 | + [StructLayout(LayoutKind.Sequential)] |
| 187 | + private struct NativeMessage |
| 188 | + { |
| 189 | + public nint Handle; |
| 190 | + public uint Message; |
| 191 | + public nint WParam; |
| 192 | + public nint LParam; |
| 193 | + public uint Time; |
| 194 | + public Point Location; |
| 195 | + } |
| 196 | + |
| 197 | + [LibraryImport("user32.dll", EntryPoint = "PeekMessageW")] |
| 198 | + private static partial int PeekMessage(out NativeMessage msg, nint hWnd, uint messageFilterMin, uint messageFilterMax, uint flags); |
| 199 | + |
| 200 | + private static bool IsApplicationIdle() => PeekMessage(out _, 0, 0, 0, 0) == 0; |
| 201 | +} |
0 commit comments