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
BlazorGpuRenderSurfaceComponent.razor.cs
1using System.Runtime.Versioning;
4using Microsoft.AspNetCore.Components;
5using Microsoft.Extensions.Logging;
6using Microsoft.JSInterop;
7using SkiaSharp;
8using SkiaSharp.Views.Blazor;
9
11
35[SupportedOSPlatform("browser")]
37{
38 [Inject] private ILogger<BlazorGpuRenderSurfaceComponent> Logger { get; set; } = null!;
39
40 private readonly string _generatedCanvasId = $"gondwana-webgl-{Guid.NewGuid():N}";
41 private BlazorSkiaGlView? _glView;
42 private IJSObjectReference? _module;
43 private GRContext? _grContext;
44 private IReadOnlyDictionary<string, object>? _gpuCanvasAttributes;
45 private string _canvasId = string.Empty;
46 private bool _backbufferNeedsRender = true;
47 private bool _disposed;
48
55 public event Action<bool>? FramePresented;
56
58 public BlazorGpuRenderSurfaceAdapter Adapter { get; private set; } = null!;
59
61 public RenderSurfaceHost<GpuBackbuffer> Host { get; private set; } = null!;
62
64 private IReadOnlyDictionary<string, object>? GpuCanvasAttributes => _gpuCanvasAttributes;
65
66 internal override ValueTask<CanvasOffset> GetCanvasOffsetAsync()
67 => _module is null
68 ? ValueTask.FromResult(default(CanvasOffset))
69 : _module.InvokeAsync<CanvasOffset>("getCanvasOffset", _canvasId);
70
71 internal override RenderSurfaceAdapterBase? InputSurfaceAdapter => Adapter;
72
74 protected override void OnInitialized()
75 {
76 try
77 {
79 Host = new RenderSurfaceHost<GpuBackbuffer>(Adapter);
80 Adapter.AttachToEngine();
81 }
82 catch (Exception ex) when (SkiaNativeInitializationDiagnostic.IsMissingSkiaNativeLibrary(ex))
83 {
84 Logger.LogError(ex, "{Guidance}", SkiaNativeInitializationDiagnostic.Guidance);
85 throw;
86 }
87 }
88
90 protected override void OnParametersSet()
91 {
92 base.OnParametersSet();
93
94 var attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
95
96 if (CanvasAttributes is not null)
97 {
98 foreach (var attribute in CanvasAttributes)
99 attributes[attribute.Key] = attribute.Value;
100 }
101
102 if (attributes.TryGetValue("id", out var id) && id is not null)
103 _canvasId = id.ToString() ?? _generatedCanvasId;
104 else
105 attributes["id"] = _canvasId = _generatedCanvasId;
106
107 attributes[nameof(SKGLView.OnPaintSurface)] =
108 (Action<SKPaintGLSurfaceEventArgs>)HandlePaintSurface;
109
110 _gpuCanvasAttributes = attributes;
111 }
112
114 protected override async Task OnAfterRenderAsync(bool firstRender)
115 {
116 if (!firstRender)
117 return;
118
119 _module = await JS.InvokeAsync<IJSObjectReference>(
120 "import",
121 "./_content/Gondwana.Blazor/gondwana-blazor.js");
122
123 try
124 {
125 await _module.InvokeVoidAsync("focusElementById", _canvasId);
126 await _module.InvokeVoidAsync("suppressBrowserInputDefaultsById", _canvasId);
127 }
128 catch
129 {
130 // Focus is best-effort; browser policy may reject programmatic focus.
131 }
132 }
133
134 private void HandlePaintSurface(SKPaintGLSurfaceEventArgs e)
135 {
136 long telemetryGeneration = Host?.Telemetry?.BeginSample() ?? 0;
137
138 if (_disposed)
139 return;
140
141 var width = e.Info.Width;
142 var height = e.Info.Height;
143 Adapter.BeginPaint(width, height);
144
145 if (width <= 0 || height <= 0 || e.Surface.Context is not GRContext grContext)
146 {
147 e.Surface.Canvas.Clear(SKColors.Black);
148 return;
149 }
150
151 var backbuffer = (GpuBackbuffer)Host.Backbuffer;
152 _grContext = grContext;
153
154 if (backbuffer.EnsureInitialized(grContext))
155 _backbufferNeedsRender = true;
156
157 var engine = Engine.Instance;
158
159 if (!engine.IsRunning)
160 {
161 e.Surface.Canvas.Clear(backbuffer.ClearColor);
162 return;
163 }
164
165 // SKGLView owns the browser rAF for the GPU path. Advance simulation first so a
166 // foreground frame request, when due, can be rendered in this same paint callback.
167 engine.Tick();
168
169 bool engineFrameRequested = Adapter.ConsumeFrameRequest();
170 bool renderScene = _backbufferNeedsRender || engineFrameRequested;
171
172 bool presented = renderScene
173 ? Host.GlRenderToCanvas(e.Surface.Canvas)
174 : Host.GlDrawCurrentFrameToCanvas(e.Surface.Canvas);
175
176 if (!presented)
177 {
178 e.Surface.Canvas.Clear(backbuffer.ClearColor);
179 return;
180 }
181
182 if (renderScene)
183 _backbufferNeedsRender = false;
184
185 // Count successful WebGL paint/presentation callbacks. This intentionally measures the
186 // browser GPU presentation cadence, which may differ from the engine's TargetFPS.
187 backbuffer.RecordFrame();
188
189 if (telemetryGeneration != 0)
190 Host!.Telemetry!.Record(telemetryGeneration, "presentation.count", 1);
191
192 FramePresented?.Invoke(renderScene);
193 }
194
196 public override void Dispose()
197 {
198 if (_disposed)
199 return;
200
201 _disposed = true;
202
203 Adapter?.Dispose();
204 Host?.Dispose();
205
206 _grContext = null;
207 _glView = null;
208
209 if (_module is not null)
210 {
211 _ = _module.DisposeAsync();
212 _module = null;
213 }
214 }
215}
Coordinates Gondwana foreground-frame requests with a Blazor WebGL render surface.
A Blazor WebGL render surface that draws Gondwana scenes through an GpuBackbuffer without transferrin...
Action< bool >? FramePresented
Raised after a WebGL frame has been successfully presented on the browser canvas. The boolean indicat...
RenderSurfaceHost< GpuBackbuffer > Host
Gets the GPU render-surface host bound to this component.
BlazorGpuRenderSurfaceAdapter Adapter
Gets the adapter that coordinates engine frame requests with this component.
Provides the shared DOM input surface used by Gondwana's Blazor bitmap and GPU render components.
IReadOnlyDictionary< string, object >? CanvasAttributes
Gets the canvas attributes with the component-owned style attribute removed.
Gives Razor a local component name for SkiaSharp's WebGL view. This avoids Razor resolving SkiaSharp ...
Represents the core game engine singleton responsible for managing the main update loop,...
Definition Engine.cs:36
void Tick()
Advances the timer-driven engine by one externally presented frame.
Definition Engine.cs:669
static Engine Instance
Gets the singleton instance of the Engine.
Definition Engine.cs:49
Provides a fully GPU-rendered backbuffer implementation using SkiaSharp and OpenGL.
Represents the abstract base class for render surface adapters that present backbuffer output to a de...
override BackbufferBase Backbuffer
Gets the backbuffer used for off-screen rendering before presentation to the adapter.
Diagnostics.? TelemetrySource Telemetry
Neutral session-local measurements for this host; null when source capacity is exhausted or the share...
bool GlDrawCurrentFrameToCanvas(SKCanvas destinationCanvas)
Draws the existing GPU backbuffer surface directly to another GPU canvas without rendering a new scen...
bool GlRenderToCanvas(SKCanvas destinationCanvas)
Renders the current scene frame and draws the GPU backbuffer surface directly to another GPU canvas....