Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
WinFormGpuRenderSurfaceAdapter.cs
4using SkiaSharp;
5using SkiaSharp.Views.Desktop;
6
8
19{
20 private readonly SKGLControl _glControl;
21 private readonly Control _presentationControl;
22 private readonly EventHandler _resizeHandler;
23
24 // ── GL-thread path ───────────────────────────────────────────────────────
25 private RenderSurfaceHostBase? _host;
26 private GpuBackbuffer? _gpuBackbuffer;
27 private Action? _afterFrameRenderHandler;
28
29 // Tracks the last VSync value applied to the GL control so we can detect changes.
30 // Null means "not yet applied" and forces an apply on the first PaintSurface call.
31 private bool? _appliedVSync;
32
33 // ── Shared state ─────────────────────────────────────────────────────────
34 // Tracks whether GrContext has been captured and the first-available event fired.
35 private bool _grContextReady;
36
37 // Set to 1 when the presentation area is resized so OnPaintSurface can fire ResizeRequested.
38 private int _pendingResize;
39
40 // Set to 1 while an invalidate callback is queued on the UI dispatcher. The callback clears
41 // the flag whether or not WinForms ultimately produces a paint, so a zero-sized presentation
42 // cannot permanently latch rendering off.
43 private int _pendingInvalidate;
44
48 public SKColor ClearColor { get; set; } = SKColors.Black;
49
53 public GRContext? GrContext { get; private set; }
54
60 public event Action<GRContext>? GrContextFirstAvailable;
61
68 public event Action<GRContext, int, int>? ResizeRequested;
69
73 public event Action<WinFormGpuFrameDiagnostics>? FrameDiagnosticsCalculated;
74
80 {
81 if (_presentationControl.IsDisposed || !_presentationControl.IsHandleCreated)
82 return;
83
84 var sz = _presentationControl.ClientSize;
85 SetDestinationSize(sz.Width, sz.Height);
86
87 if (sz.Width > 0 && sz.Height > 0)
88 Interlocked.Exchange(ref _pendingResize, 1);
89 else
90 Interlocked.Exchange(ref _pendingResize, 0);
91 }
92
97 public WinFormGpuRenderSurfaceAdapter(SKGLControl gl)
98 : this(gl, gl)
99 {
100 }
101
108 internal WinFormGpuRenderSurfaceAdapter(SKGLControl gl, Control presentationControl)
109 : base(
110 Math.Max(1, presentationControl.ClientSize.Width),
111 Math.Max(1, presentationControl.ClientSize.Height),
112 presentationControl.ClientSize.Width > 0 && presentationControl.ClientSize.Height > 0)
113 {
114 _glControl = gl ?? throw new ArgumentNullException(nameof(gl));
115 _presentationControl = presentationControl ?? throw new ArgumentNullException(nameof(presentationControl));
116
117 // Track the actual presentation control rather than the GL drawable. The wrapper may keep
118 // the drawable at 1×1 while its own client area is 0×0 so OpenTK/GLFW never receives a
119 // zero-sized native surface.
120 _resizeHandler = (_, _) => RefreshDestinationSize();
121
122 // Wire events
123 _glControl.PaintSurface += OnPaintSurface;
124 _presentationControl.Resize += _resizeHandler;
125
126 // On modern SkiaSharp, SKGLControl exposes GRContext; otherwise capture it in the first paint.
127 GrContext = _glControl.GRContext; // may be null until first paint; we also set in OnPaintSurface
128 }
129
143 {
144 _host = host ?? throw new ArgumentNullException(nameof(host));
145 _host.Telemetry?.Define("presentation.cpu.ms");
146 _host.Telemetry?.Define("render.snapshot.cpu.ms");
147 _host.Telemetry?.Define("blit.cpu.ms");
148 _host.Telemetry?.Define("flush.cpu.ms");
149
150 // Cache the GpuBackbuffer so OnPaintSurface can read its settings.
151 _gpuBackbuffer = _host.Backbuffer as GpuBackbuffer;
152
153 // Invalidate the GL control on the UI thread after every engine foreground cycle.
154 // _pendingInvalidate tracks the queued dispatcher callback, not PaintSurface itself.
155 // Invalidate() is only a paint request and can be dropped while the presentation has no
156 // area, so tying this latch to PaintSurface can permanently starve rendering after restore.
157 _afterFrameRenderHandler = QueueInvalidate;
158 Engine.Instance.AfterFrameRender += _afterFrameRenderHandler;
159 }
160
168 public override void Present(SKImage bufferImage, SKRectI bufferRect, SKRect destRect)
169 {
170 bufferImage.Dispose();
171 }
172
173 private void QueueInvalidate()
174 {
175 if (_glControl.IsDisposed || _presentationControl.IsDisposed)
176 return;
177
178 if (Interlocked.CompareExchange(ref _pendingInvalidate, 1, 0) != 0)
179 return;
180
182 {
183 try
184 {
185 if (!_glControl.IsDisposed
186 && !_presentationControl.IsDisposed
187 && _presentationControl.ClientSize.Width > 0
188 && _presentationControl.ClientSize.Height > 0)
189 {
190 _glControl.Invalidate();
191 }
192 }
193 finally
194 {
195 // The dispatcher callback completed. Do not wait for PaintSurface: WinForms is
196 // allowed to coalesce or discard an invalidation, especially at zero size.
197 Interlocked.Exchange(ref _pendingInvalidate, 0);
198 }
199 });
200 }
201
202 private void OnPaintSurface(object? sender, SKPaintGLSurfaceEventArgs e)
203 {
204 long telemetryGeneration = _host?.Telemetry?.BeginSample() ?? 0;
205 bool collectDiagnostics = FrameDiagnosticsCalculated is not null || telemetryGeneration != 0;
206 long callbackStartTick = collectDiagnostics ? HighResTimer.GetCurrentTick() : 0;
207 long renderAndSnapshotTicks = 0;
208 long blitTicks = 0;
209 long flushTicks = 0;
210
211 // Lazily sync VSync → GLControl.VSync whenever the backbuffer value changes.
212 if (_gpuBackbuffer != null)
213 {
214 bool desiredVSync = _gpuBackbuffer.VSync;
215
216 if (_appliedVSync != desiredVSync)
217 {
218 _glControl.VSync = desiredVSync;
219 _appliedVSync = desiredVSync;
220 }
221 }
222
223 // Capture/refresh the GRContext so callers can wire the backbuffer to the same one.
224 GrContext = _glControl.GRContext;
225
226 if (GrContext != null)
227 {
228 if (!_grContextReady)
229 {
230 // First time the context is available: clear any resize that happened before the
231 // first paint (the Initialize call will use the current adapter dimensions).
232 _grContextReady = true;
233 Interlocked.Exchange(ref _pendingResize, 0);
235 }
236 else if (Interlocked.Exchange(ref _pendingResize, 0) == 1)
237 {
238 // Notify consumers about presentation resource resize on the GL thread.
239 // WinForms controls can report zero size while minimized or before layout completes;
240 // suppress invalid resize requests so downstream GPU initialization is not attempted
241 // with non-positive dimensions.
242 var width = Width;
243 var height = Height;
244
245 if (width > 0 && height > 0)
246 ResizeRequested?.Invoke(GrContext, width, height);
247 }
248 }
249
250 if (GrContext != null)
251 _gpuBackbuffer?.EnsureInitialized(GrContext);
252
253 var canvas = e.Surface.Canvas;
254
255 // The physical GL drawable is intentionally kept at least 1×1, even when the wrapper has
256 // no presentation area. Avoid doing scene work for that clipped placeholder surface.
257 if (Width <= 0 || Height <= 0)
258 {
259 canvas.Clear(ClearColor);
260 return;
261 }
262
263 // Render + blit entirely on the GL thread.
264 // GlRenderAndSnapshot replays immutable Engine commands on the GPU surface and returns a
265 // lightweight GPU-backed snapshot. Both the snapshot texture and e.Surface share the
266 // same GRContext, so DrawImage is a zero-copy GPU blit.
267 if (_host != null)
268 {
269 long renderStartTick = collectDiagnostics ? HighResTimer.GetCurrentTick() : 0;
270 using var img = _host.GlRenderAndSnapshot();
271 long renderEndTick = collectDiagnostics ? HighResTimer.GetCurrentTick() : 0;
272
273 if (collectDiagnostics)
274 renderAndSnapshotTicks = renderEndTick - renderStartTick;
275
276 if (img != null)
277 {
278 long blitStartTick = collectDiagnostics ? HighResTimer.GetCurrentTick() : 0;
279 DrawImage(canvas, img, ClearColor);
280 long blitEndTick = collectDiagnostics ? HighResTimer.GetCurrentTick() : 0;
281
282 if (collectDiagnostics)
283 blitTicks = blitEndTick - blitStartTick;
284 }
285 else
286 {
287 canvas.Clear(ClearColor);
288 }
289 }
290 else
291 {
292 canvas.Clear(ClearColor);
293 }
294
295 // Optional: flush to ensure work is queued to GPU before we hand new images next frame.
296 long flushStartTick = collectDiagnostics ? HighResTimer.GetCurrentTick() : 0;
297 _glControl.GRContext?.Flush();
298 long flushEndTick = collectDiagnostics ? HighResTimer.GetCurrentTick() : 0;
299
300 if (collectDiagnostics)
301 flushTicks = flushEndTick - flushStartTick;
302
303 // Record the completed frame so the engine's CPS sampler can compute actual rendered FPS.
304 _gpuBackbuffer?.RecordFrame();
305
306 if (collectDiagnostics)
307 {
308 long callbackEndTick = HighResTimer.GetCurrentTick();
309
310 if (telemetryGeneration != 0)
311 {
312 var source = _host!.Telemetry!;
313 source.Record(telemetryGeneration, "presentation.count", 1);
314
315 source.Record(
316 telemetryGeneration,
317 "presentation.cpu.ms",
318 HighResTimer.GetDuration(callbackStartTick, callbackEndTick) * 1000d);
319
320 source.Record(
321 telemetryGeneration,
322 "render.snapshot.cpu.ms",
323 HighResTimer.GetDuration(0, renderAndSnapshotTicks) * 1000d);
324
325 source.Record(telemetryGeneration, "blit.cpu.ms", HighResTimer.GetDuration(0, blitTicks) * 1000d);
326 source.Record(telemetryGeneration, "flush.cpu.ms", HighResTimer.GetDuration(0, flushTicks) * 1000d);
327 }
328
331 HighResTimer.GetDuration(callbackStartTick, callbackEndTick) * 1000d,
332 HighResTimer.GetDuration(0, renderAndSnapshotTicks) * 1000d,
333 HighResTimer.GetDuration(0, blitTicks) * 1000d,
334 HighResTimer.GetDuration(0, flushTicks) * 1000d));
335 }
336 }
337
341 public void Dispose()
342 {
343 if (_afterFrameRenderHandler != null)
344 {
345 Engine.Instance.AfterFrameRender -= _afterFrameRenderHandler;
346 _afterFrameRenderHandler = null;
347 }
348
349 if (!_glControl.IsDisposed)
350 _glControl.PaintSurface -= OnPaintSurface;
351
352 if (!_presentationControl.IsDisposed)
353 _presentationControl.Resize -= _resizeHandler;
354 }
355}
Represents the core game engine singleton responsible for managing the main update loop,...
Definition Engine.cs:36
static Engine Instance
Gets the singleton instance of the Engine.
Definition Engine.cs:49
IUiDispatcher? UiDispatcher
Gets the UI dispatcher used for marshalling operations to the UI thread.
Definition Engine.cs:815
Provides a fully GPU-rendered backbuffer implementation using SkiaSharp and OpenGL.
int Width
Gets the current width of the render surface in pixels.
void SetDestinationSize(int destWidth, int destHeight)
Sets the destination size of the render surface and raises the Resized event if the dimensions have c...
RenderSurfaceAdapterBase(int destWidth, int destHeight)
Initializes a new instance of the RenderSurfaceAdapterBase class with the specified dimensions.
int Height
Gets the current height of the render surface in pixels.
void DrawImage(SKCanvas canvas, SKImage image, SKColor clearColor)
Presents a complete image using the same transform as pointer normalization.
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
Action< WinFormGpuFrameDiagnostics >? FrameDiagnosticsCalculated
Occurs after a completed GPU paint callback when a subscriber requests timing diagnostics.
void SetHost(RenderSurfaceHostBase host)
Registers the RenderSurfaceHostBase whose scene this adapter should render and wires the GL paint loo...
override void Present(SKImage bufferImage, SKRectI bufferRect, SKRect destRect)
Not used in the GL-thread path. Rendering is driven by SetHost and SKGLControl.PaintSurface....
Action< GRContext >? GrContextFirstAvailable
Raised once, the first time the GRContext becomes available in OnPaintSurface. Subscribe to this even...
Action< GRContext, int, int >? ResizeRequested
Raised on the GL thread when the control has been resized and a valid GRContext is available....
void Dispose()
Releases all resources used by the WinFormGpuRenderSurfaceAdapter.
GRContext? GrContext
Gets the GL/Skia GPU context that should be shared with the GpuBackbuffer.
void RefreshDestinationSize()
Refreshes the destination size based on the current client size of the presentation control....
SKColor ClearColor
Gets or sets the color used to clear the surface before rendering.
WinFormGpuRenderSurfaceAdapter(SKGLControl gl)
Initializes a new instance of the WinFormGpuRenderSurfaceAdapter class.
void Post(Action action)
Asynchronously posts an action to be executed on the UI thread. This method queues the action and ret...
record WinFormGpuFrameDiagnostics(double TotalCallbackMilliseconds, double RenderAndSnapshotMilliseconds, double BlitMilliseconds, double FlushMilliseconds)
Captures measured work performed by one WinForms GPU paint callback.