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
GpuBackbuffer.cs
1using System.Drawing;
4using SkiaSharp;
5
7
39public class GpuBackbuffer : BackbufferBase
40{
41 // Surface state. All access MUST occur on the GL thread after Initialize() is called.
42 private SKBitmap? _cpuBitmap; // temporary CPU surface used before GRContext is ready
43 private SKSurface? _surface;
44 private bool _disposed;
45 private GRContext? _context;
46
47 private sealed record Resolution(int Width, int Height);
48
49 private Resolution? _requestedResolution;
50
51 private int _targetFps = 60;
52 private readonly object _msaaSyncRoot = new();
53 private int _msaaSampleCount = 1;
54 private long _msaaConfigurationRevision;
55 private long _appliedMsaaConfigurationRevision = -1;
56 private int _actualMsaaSampleCount = 1;
57 private int _maxSupportedMsaaSampleCount = 1;
58
59 // Frame counter used to compute the actual rendered FPS.
60 // Incremented on the GL thread by RecordFrame(); consumed atomically by the engine's CPS sampler.
61 private long _frameCount;
62
75 public int TargetFps
76 {
77 get => _targetFps;
78 set => _targetFps = value < 0 ? 0 : value;
79 }
80
101 public bool VSync { get; set; } = true;
102
132 {
133 get
134 {
135 lock (_msaaSyncRoot)
136 return _msaaSampleCount;
137 }
138 set
139 {
140 int normalized = value < 1 ? 1 : value;
141
142 lock (_msaaSyncRoot)
143 {
144 if (_msaaSampleCount == normalized)
145 return;
146
147 _msaaSampleCount = normalized;
148 _msaaConfigurationRevision++;
149 }
150 }
151 }
152
162 public int ActualMsaaSampleCount => Volatile.Read(ref _actualMsaaSampleCount);
163
172 public int MaxSupportedMsaaSampleCount => Volatile.Read(ref _maxSupportedMsaaSampleCount);
173
177 internal bool IsMsaaSurfaceRecreationPending =>
178 Volatile.Read(ref _appliedMsaaConfigurationRevision) !=
179 Volatile.Read(ref _msaaConfigurationRevision);
180
186 public GpuBackbuffer(int width, int height)
187 : base(width, height)
188 {
189 // Apply the current engine configuration defaults for the settings this backbuffer
190 // explicitly copies at construction time: TargetFps, VSync, and MsaaSampleCount.
191 var config = Engine.Instance.Configuration;
192 TargetFps = config.TargetFPS;
193 VSync = config.VSync;
194 MsaaSampleCount = config.MsaaSampleCount;
195
196 CreateCpuSurface(width, height);
197 }
198
204 public override bool IsGlThreadRendered => true;
205
217 public void Initialize(GRContext grContext, int width, int height)
218 {
219 if (width <= 0 || height <= 0)
220 return;
221
222 if (_disposed)
223 return;
224
225 (int requestedSampleCount, long configurationRevision) = GetMsaaConfigurationSnapshot();
226 int maxSupportedSampleCount = grContext.GetMaxSurfaceSampleCount(SKColorType.Rgba8888);
227 Volatile.Write(ref _maxSupportedMsaaSampleCount, maxSupportedSampleCount);
228
229 DisposeSurface();
230
231 int actualSampleCount = CreateGpuSurface(
232 grContext,
233 width,
234 height,
235 requestedSampleCount);
236
237 _context = grContext;
238
239 // SizeChanged updates live viewports. Only this handoff needs the simulation
240 // gate; GPU creation and ordinary command replay never hold it.
241 lock (RenderStateSynchronization.SyncRoot)
242 UpdateSize(width, height);
243
244 MarkMsaaConfigurationApplied(configurationRevision, actualSampleCount);
245
246 // Set canvas into a known state for the first frame on the new surface.
247 BeginFrame();
248 Canvas.Clear(ClearColor);
249 }
250
256 protected internal override void RequestResize(int width, int height)
257 => Interlocked.Exchange(ref _requestedResolution, new(width, height));
258
266 public bool EnsureInitialized(GRContext context)
267 {
268 ArgumentNullException.ThrowIfNull(context);
269
270 if (_disposed)
271 return false;
272
273 var request = Interlocked.Exchange(ref _requestedResolution, null);
274 int width = request?.Width ?? Width;
275 int height = request?.Height ?? Height;
276
277 if (ReferenceEquals(_context, context) &&
278 width == Width &&
279 height == Height &&
280 !IsMsaaSurfaceRecreationPending)
281 {
282 return false;
283 }
284
285 Initialize(context, width, height);
286 return true;
287 }
288
292 public override SKCanvas Canvas => _surface?.Canvas
293 ?? throw new InvalidOperationException(
294 $"{nameof(GpuBackbuffer)} surface is not initialized.");
295
299 protected internal override void BeginFrame()
300 {
301 if (_disposed || _surface is null)
302 return;
303
304 var c = _surface.Canvas;
305 c.RestoreToCount(1);
306 c.Save();
307 c.ResetMatrix();
308
309 c.ClipRect(
310 new SKRect(
311 0,
312 0,
313 Width,
314 Height));
315 }
316
320 protected internal override void EndFrame()
321 {
322 if (_disposed || _surface is null)
323 return;
324
325 _surface.Flush();
326 }
327
333 protected internal override void DrawTileFrame(Tile tile, RectangleF destRectScreen)
334 {
335 var image = tile.CurrentFrame.SkImage;
336
337 if (image is null || _surface is null)
338 return;
339
340 var canvas = _surface.Canvas;
341
342 canvas.DrawImage(image, destRectScreen.ToSKRect());
343 }
344
355 protected internal override SKImage Snapshot()
356 {
357 if (_disposed || _surface is null)
358 throw new ObjectDisposedException(nameof(GpuBackbuffer));
359
360 return _surface.Snapshot();
361 }
362
363 // ── Actual FPS tracking ──────────────────────────────────────────────────
364
369 public void RecordFrame() => Interlocked.Increment(ref _frameCount);
370
376 internal long ConsumeFrameCount() => Interlocked.Exchange(ref _frameCount, 0);
377
378 // ── Surface creation helpers ─────────────────────────────────────────────
379
380 internal (int SampleCount, long Revision) GetMsaaConfigurationSnapshot()
381 {
382 lock (_msaaSyncRoot)
383 return (_msaaSampleCount, _msaaConfigurationRevision);
384 }
385
386 internal void MarkMsaaConfigurationApplied(long revision, int actualSampleCount)
387 {
388 Volatile.Write(ref _actualMsaaSampleCount, actualSampleCount);
389 Volatile.Write(ref _appliedMsaaConfigurationRevision, revision);
390 }
391
392 private int CreateGpuSurface(
393 GRContext grContext,
394 int width,
395 int height,
396 int requestedSampleCount)
397 {
398 // Rgba8888 / Premul is the natural format for an OpenGL render target.
399 var info = new SKImageInfo(
400 width,
401 height,
402 SKColorType.Rgba8888,
403 SKAlphaType.Premul);
404
405 _surface = SKSurface.Create(
406 grContext,
407 budgeted: true,
408 info,
409 requestedSampleCount);
410
411 if (_surface is not null)
412 return requestedSampleCount;
413
414 // SKSurface.Create returns null when the requested MSAA sample count is not supported
415 // by the hardware or driver. Fall back to no MSAA (sample count 1) so the surface
416 // is always valid after Initialize() completes.
417 if (requestedSampleCount > 1)
418 _surface = SKSurface.Create(
419 grContext,
420 budgeted: true,
421 info,
422 sampleCount: 1);
423
424 if (_surface is null)
425 throw new InvalidOperationException(
426 $"Failed to create a {nameof(GpuBackbuffer)} GPU surface ({width}x{height}). " +
427 "The GRContext may be invalid or the pixel format is not renderable.");
428
429 return 1;
430 }
431
432 private void CreateCpuSurface(int width, int height)
433 {
434 // Bgra8888 matches the native Windows GDI pixel format; used only before
435 // GRContext becomes available so rendering is always valid from frame one.
436 var info = new SKImageInfo(
437 width,
438 height,
439 SKColorType.Bgra8888,
440 SKAlphaType.Premul);
441
442 _cpuBitmap = new SKBitmap(info);
443 _surface = SKSurface.Create(info, _cpuBitmap.GetPixels(), _cpuBitmap.Info.RowBytes);
444 }
445
446 private void DisposeSurface()
447 {
448 _surface?.Dispose();
449 _surface = null;
450 _cpuBitmap?.Dispose();
451 _cpuBitmap = null;
452 }
453
454 // Called by a platform's GL deinitialization callback, while its old context
455 // is still current. Logical state and Engine-owned recordings survive a
456 // temporary context loss; EnsureInitialized will attach the next context.
457 internal void ReleaseContext()
458 {
459 DisposeSurface();
460 _context = null;
461 }
462
466 public override void Dispose()
467 {
468 if (_disposed)
469 return;
470
471 _disposed = true;
472 base.Dispose();
473 DisposeSurface();
474 GC.SuppressFinalize(this);
475 }
476}
Represents an abstract base class for drawable tiles in the Gondwana engine. Provides core functional...
Definition Tile.cs:19
virtual Frame CurrentFrame
Gets or sets the current frame. The initial frame supplies the tile's default collision adjustment an...
Definition Tile.cs:185
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
EngineConfiguration Configuration
Gets the current engine configuration settings.
Definition Engine.cs:952
int Width
Gets the current Backbuffer width in a thread-safe manner.
void UpdateSize(int width, int height)
Updates the stored backbuffer dimensions and raises the SizeChanged event.
int Height
Gets the current Backbuffer height in a thread-safe manner.
SKColor ClearColor
Gets or sets the color used to clear the drawing surface.
bool VSync
Gets or sets a value indicating whether vertical synchronisation (vsync) is enabled.
int ActualMsaaSampleCount
Gets the sample count used by the currently active GPU render-target surface.
int MsaaSampleCount
Gets or sets the number of MSAA (multisample anti-aliasing) samples used when creating the GPU render...
GpuBackbuffer(int width, int height)
Initializes a new instance of the GpuBackbuffer class with the specified dimensions.
int MaxSupportedMsaaSampleCount
Gets the maximum MSAA sample count reported by the active GPU context for SKColorType....
void Initialize(GRContext grContext, int width, int height)
Creates (or recreates) the GPU render-target surface for this backbuffer.
int TargetFps
Gets or sets the target frame rate associated with this GPU backbuffer.
bool EnsureInitialized(GRContext context)
Initializes on the owning GL thread, or applies an explicit logical resolution request....
void RecordFrame()
Records that one frame has been rendered. Called by the platform adapter on every PaintSurface callba...
override void Dispose()
Releases all resources used by this GpuBackbuffer.
override SKCanvas Canvas
Gets the SkiaSharp canvas for drawing operations.
readonly? SKImage SkImage
Gets the SkiaSharp image for this frame.
Definition Frame.cs:74