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
SplashScreen.cs
1using System.Drawing;
7using Microsoft.Extensions.Logging;
8using SkiaSharp;
10
12
32public sealed class SplashScreen : WidgetBase
33{
34 private static readonly ILogger<SplashScreen> Logger =
35 EngineLogger.GetLogger<SplashScreen>();
36
40 public enum State
41 {
46
51
56
61 }
62
66 public static readonly string SplashImageNickname = "__gondwana_splash__";
67
68 private readonly View _view;
69 private Timer? _holdTimer;
70 private TaskCompletionSource? _holdDurationCompletionSource;
71 private bool _disposed;
72
73 #region properties
74
78 public DirectImage Image { get; private set; }
79
83 public State CurrentState { get; private set; }
84
88 public float FadeInSec { get; private set; }
89
94 public float HoldSec { get; private set; }
95
99 public float FadeOutSec { get; private set; }
100
101 #endregion properties
102
103 #region factory / constructor
104
105 private SplashScreen(
106 DirectImage image,
107 float fadeInSec,
108 float holdSec,
109 float fadeOutSec,
110 Action? onHoldingSync,
111 Func<Task>? onHoldingAsync,
112 Action? onSplashCompleted)
113 : base(
114 image.RenderSurfaceHost,
116 PointF.Empty,
117 SplashImageNickname + Guid.NewGuid())
118 {
119 Image = image;
120
121 _view = image.View
122 ?? throw new InvalidOperationException("Splash image must be attached to a view.");
123
124 _view.Viewport.TargetRectChanged += OnViewportTargetRectChanged;
125 CurrentState = State.Hidden;
126
127 FadeInSec = fadeInSec;
128 HoldSec = holdSec;
129 FadeOutSec = fadeOutSec;
130
131 Add(Image);
132
133 StartFadeIn(
134 onHoldingSync,
135 onHoldingAsync,
136 onSplashCompleted);
137 }
138
201 public static SplashScreen? TryCreate(
202 Stream imageStream,
204 View view,
205 float fadeInSec = 0.45f,
206 float holdSec = 3f,
207 float fadeOutSec = 0.45f,
208 Action? onHoldingSync = null,
209 Func<Task>? onHoldingAsync = null,
210 Action? onSplashCompleted = null)
211 {
212 if (host.ViewManager.Views.Count == 0)
213 return null;
214
215 using var bitmap = SKBitmap.Decode(imageStream);
216
217 var sourceImage = bitmap is null
218 ? null
219 : SKImage.FromBitmap(bitmap);
220
221 if (sourceImage is null)
222 return null;
223
224 var viewport = view.Viewport.TargetRectPx;
225
226 var screenBounds = viewport;
227
228 var image = new DirectImage(
229 sourceImage,
230 host,
231 view,
232 screenBounds,
235
236 // DirectImage does not own the SKImage lifetime.
237 image.Disposing += (_, _) => sourceImage.Dispose();
238
239 image.ZOrder = int.MaxValue;
240 image.Opacity = 0f;
241
242 return new SplashScreen(
243 image,
244 fadeInSec,
245 holdSec,
246 fadeOutSec,
247 onHoldingSync,
248 onHoldingAsync,
249 onSplashCompleted);
250 }
251
252 #endregion factory / constructor
253
257 public override void Dispose()
258 {
259 if (_disposed)
260 return;
261
262 _disposed = true;
263
264 _view.Viewport.TargetRectChanged -= OnViewportTargetRectChanged;
265
266 _holdTimer?.Dispose();
267 _holdTimer = null;
268
269 _holdDurationCompletionSource?.TrySetCanceled();
270 _holdDurationCompletionSource = null;
271
272 base.Dispose();
273 }
274
275 private void OnViewportTargetRectChanged(ViewportResizedEventArgs args)
276 {
277 if (_disposed)
278 return;
279
280 Image.ScreenBounds = args.NewRect;
281 }
282
283 #region splash control
284
285 private void StartFadeIn(Action? onHoldingSync, Func<Task>? onHoldingAsync, Action? onSplashCompleted)
286 {
287 Logger.LogDebug("Starting splash screen fade-in");
288
289 CurrentState = State.FadingIn;
290
291 EventHandler<DirectDrawingBase>? fadeInHandler = null;
292
293 fadeInHandler = (_, _) =>
294 {
295 Image.FadeToCompleted -= fadeInHandler;
296
297 if (_disposed)
298 return;
299
300 CurrentState = State.Holding;
301
302 _ = RunHoldPhaseAsync(
303 onHoldingSync,
304 onHoldingAsync,
305 onSplashCompleted);
306 };
307
308 Image.FadeToCompleted += fadeInHandler;
309
311 }
312
313 private async Task RunHoldPhaseAsync(
314 Action? onHoldingSync,
315 Func<Task>? onHoldingAsync,
316 Action? onSplashCompleted)
317 {
318 Logger.LogDebug("Starting splash screen hold phase");
319
320 try
321 {
322 var holdDurationTask = WaitForHoldDurationAsync();
323
324 var delegateTask = ExecuteHoldDelegatesAsync(onHoldingSync, onHoldingAsync);
325
326 await Task.WhenAll(
327 holdDurationTask,
328 delegateTask);
329 }
330 catch (OperationCanceledException)
331 when (_disposed)
332 {
333 return;
334 }
335 catch (Exception ex)
336 {
337 Logger.LogError(ex, "Unexpected error during SplashScreen hold phase");
338 }
339 finally
340 {
341 _holdTimer?.Dispose();
342 _holdTimer = null;
343
344 _holdDurationCompletionSource = null;
345 }
346
347 if (_disposed)
348 return;
349
350 Engine.Instance.EngineDispatcher.Post(() =>
351 {
352 if (_disposed)
353 return;
354
355 if (CurrentState != State.Holding)
356 return;
357
358 StartFadeOut(onSplashCompleted);
359 });
360 }
361
362 private Task WaitForHoldDurationAsync()
363 {
364 var completionSource = new TaskCompletionSource(
365 TaskCreationOptions.RunContinuationsAsynchronously);
366
367 _holdDurationCompletionSource =
368 completionSource;
369
370 var timer = Timer.Add(
371 TimerType.PostCycle,
372 TimerCycles.Once,
373 HoldSec);
374
375 _holdTimer = timer;
376
377 void OnHoldTimerElapsed()
378 {
379 timer.Tick -= OnHoldTimerElapsed;
380
381 completionSource.TrySetResult();
382 }
383
384 timer.Tick += OnHoldTimerElapsed;
385
386 return completionSource.Task;
387 }
388
389 private static async Task ExecuteHoldDelegatesAsync(
390 Action? onHoldingSync,
391 Func<Task>? onHoldingAsync)
392 {
393 if (onHoldingSync is null &&
394 onHoldingAsync is null)
395 {
396 return;
397 }
398
399 var dispatcher =
400 Engine.Instance.EngineDispatcher;
401
402 try
403 {
404 await dispatcher.PostAsync(async () =>
405 {
406 Task asyncTask =
407 Task.CompletedTask;
408
409 Task syncTask =
410 Task.CompletedTask;
411
412 if (onHoldingAsync is not null)
413 {
414 Logger.LogDebug("Calling onHoldingAsync in SplashScreen");
415
416 try
417 {
418 asyncTask = onHoldingAsync() ?? Task.CompletedTask;
419 }
420 catch (Exception ex)
421 {
422 asyncTask = Task.FromException(ex);
423 }
424 }
425
426 if (onHoldingSync is not null)
427 {
428 Logger.LogDebug("Calling onHoldingSync in SplashScreen");
429
430 try
431 {
432 onHoldingSync();
433 }
434 catch (Exception ex)
435 {
436 syncTask = Task.FromException(ex);
437 }
438 }
439
440 await Task.WhenAll(asyncTask, syncTask);
441 });
442 }
443 catch (Exception ex)
444 {
445 Logger.LogError(ex, "Error executing SplashScreen hold delegates");
446 }
447 }
448
449 private void StartFadeOut(Action? onSplashCompleted)
450 {
451 Logger.LogDebug("Starting splash screen fade-out");
452
453 CurrentState = State.FadingOut;
454
455 EventHandler<DirectDrawingBase>? fadeOutHandler = null;
456
457 fadeOutHandler = (_, _) =>
458 {
459 Image.FadeToCompleted -= fadeOutHandler;
460 CurrentState = State.Hidden;
461 Dispose();
462 onSplashCompleted?.Invoke();
463 };
464
465 Image.FadeToCompleted += fadeOutHandler;
466 Image.FadeOut(FadeOutSec);
467 }
468
469 #endregion splash control
470}
RenderSurfaceHostBase RenderSurfaceHost
Gets the render surface host shared by the composite and its children.
View? View
Gets the view shared by all children in view mode.
virtual DirectComposite Add(IDirectCompositeChild child, bool keepCurrentOffset=true, Vector2? explicitLocalOffsetPx=null)
Adds a composite-compatible direct drawable as a child.
void Dispose()
Releases all resources used by this DirectDrawingBase instance.
DirectDrawingBase FadeIn(float durationSec)
Fades this direct drawing from its current opacity to fully opaque over the specified duration.
Renders a bitmap or image to a rectangular region with support for scaling modes, source clipping,...
DirectImage SetScaleMode(ScaleMode mode)
Sets how the image is scaled to fit within the destination rectangle.
ScaleMode
Defines how an image is scaled to fit within the destination rectangle.
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
ViewManager ViewManager
Gets the view manager that controls camera positions, viewports, and multi-view rendering for this re...
ReadOnlyCollection< View > Views
Gets a read-only collection of all views currently managed by this view manager. Views are sorted by ...
Represents a rendered view of a scene, combining a camera position with a viewport configuration to c...
Definition View.cs:14
Viewport Viewport
Gets the viewport that defines the screen-space rectangle, zoom level, and other rendering parameters...
Definition View.cs:44
Provides data for the Viewport.TargetRectChanged event, which is raised when a viewport's target rect...
Rectangle NewRect
Gets the new target rectangle after the resize or reposition operation.
Rectangle TargetRectPx
Screen-space rectangle (in SCREEN / RenderSurface pixels) where this view is drawn....
Definition Viewport.cs:40
Represents a high-resolution timer that can trigger events at specified intervals and supports variou...
Definition Timer.cs:16
static Timer Add(string timerID, TimerType type, TimerCycles cycles, double length)
Creates a new timer with the specified parameters and adds it to the collection of active timers.
Definition Timer.cs:144
Represents a full-screen splash screen widget that fades in, holds for a duration,...
float FadeOutSec
Gets the duration of the fade-out animation in seconds.
State
Represents the current state of the splash screen animation.
@ Holding
The splash screen is held at full opacity.
@ FadingOut
The splash screen is fading out from opaque to transparent.
@ FadingIn
The splash screen is fading in from transparent to opaque.
@ Hidden
The splash screen is not visible.
State CurrentState
Gets the current state of the splash screen.
static readonly string SplashImageNickname
The nickname used for the DirectImage overlay that displays the splash.
float HoldSec
Gets the minimum duration for which the splash remains at full opacity, in seconds.
override void Dispose()
Releases the splash overlay and associated resources.
DirectImage Image
Gets the DirectImage overlay that displays the splash image.
static ? SplashScreen TryCreate(Stream imageStream, RenderSurfaceHostBase host, View view, float fadeInSec=0.45f, float holdSec=3f, float fadeOutSec=0.45f, Action? onHoldingSync=null, Func< Task >? onHoldingAsync=null, Action? onSplashCompleted=null)
Attempts to create a new SplashScreen instance from the provided image stream.
float FadeInSec
Gets the duration of the fade-in animation in seconds.
WidgetBase(RenderSurfaceHostBase renderSurfaceHost, DirectDrawingMode mode, PointF anchor=default, string? nickname=null)
Initializes a new instance of the WidgetBase class.
Definition WidgetBase.cs:95
DirectDrawingMode
Specifies where direct drawing operations are applied within the rendering pipeline.
TimerType
Specifies when a Timer should have its Timer.Tick event raised relative to the engine's main update a...
Definition TimerType.cs:22
TimerCycles
Specifies the cycle behavior of a Timer, determining whether it executes once or repeatedly at its co...