forked from ppy/osu-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameHost.cs
1273 lines (1014 loc) · 50.8 KB
/
GameHost.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json;
using osuTK;
using osuTK.Graphics.ES30;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Development;
using osu.Framework.Extensions.ExceptionExtensions;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL;
using osu.Framework.Graphics.Rendering;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Handlers;
using osu.Framework.Logging;
using osu.Framework.Statistics;
using osu.Framework.Threading;
using osu.Framework.Timing;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Video;
using osu.Framework.IO.Serialization;
using osu.Framework.IO.Stores;
using osu.Framework.Localisation;
using Image = SixLabors.ImageSharp.Image;
using PixelFormat = osuTK.Graphics.ES30.PixelFormat;
using Size = System.Drawing.Size;
namespace osu.Framework.Platform
{
public abstract class GameHost : IIpcHost, IDisposable
{
public IWindow Window { get; private set; }
public IRenderer Renderer { get; private set; }
/// <summary>
/// Whether "unlimited" frame limiter should be allowed to exceed sane limits.
/// Only use this for benchmarking purposes (see <see cref="maximum_sane_fps"/> for further reasoning).
/// </summary>
public bool AllowBenchmarkUnlimitedFrames { get; set; }
protected FrameworkDebugConfigManager DebugConfig { get; private set; }
protected FrameworkConfigManager Config { get; private set; }
private InputConfigManager inputConfig { get; set; }
/// <summary>
/// Whether the <see cref="IWindow"/> is active (in the foreground).
/// </summary>
public readonly IBindable<bool> IsActive = new Bindable<bool>(true);
/// <summary>
/// Disable any system level timers that might dim or turn off the screen.
/// </summary>
/// <remarks>
/// To preserve battery life on mobile devices, this should be left on whenever possible.
/// </remarks>
public readonly AggregateBindable<bool> AllowScreenSuspension = new AggregateBindable<bool>((a, b) => a & b, new Bindable<bool>(true));
/// <summary>
/// For IPC messaging purposes, whether this <see cref="GameHost"/> is the primary (bound) host.
/// </summary>
public virtual bool IsPrimaryInstance { get; protected set; } = true;
/// <summary>
/// Invoked when the game window is activated. Always invoked from the update thread.
/// </summary>
public event Action Activated;
/// <summary>
/// Invoked when the game window is deactivated. Always invoked from the update thread.
/// </summary>
public event Action Deactivated;
/// <summary>
/// Invoked when an exit was requested. Always invoked from the update thread.
/// </summary>
/// <remarks>
/// Usually invoked when the window close (X) button or another platform-native exit action has been pressed.
/// </remarks>
public event Action ExitRequested;
public event Action Exited;
/// <summary>
/// An unhandled exception was thrown. Return true to ignore and continue running.
/// </summary>
public event Func<Exception, bool> ExceptionThrown;
public event Func<IpcMessage, IpcMessage> MessageReceived;
/// <summary>
/// Whether the on screen keyboard covers a portion of the game window when presented to the user.
/// </summary>
public virtual bool OnScreenKeyboardOverlapsGameWindow => false;
/// <summary>
/// Whether this host can exit (mobile platforms, for instance, do not support exiting the app).
/// </summary>
/// <remarks>Also see <see cref="CanSuspendToBackground"/>.</remarks>
public virtual bool CanExit => true;
/// <summary>
/// Whether this host can suspend and minimize to background.
/// </summary>
/// <remarks>
/// This and <see cref="SuspendToBackground"/> are an alternative way to exit on hosts that have <see cref="CanExit"/> <c>false</c>.
/// </remarks>
public virtual bool CanSuspendToBackground => false;
protected IpcMessage OnMessageReceived(IpcMessage message) => MessageReceived?.Invoke(message);
public virtual Task SendMessageAsync(IpcMessage message) => throw new NotSupportedException("This platform does not implement IPC.");
/// <summary>
/// Requests that a file be opened externally with an associated application, if available.
/// </summary>
/// <remarks>
/// Some platforms do not support interacting with files externally (ie. mobile or sandboxed platforms), check the return value as to whether it succeeded.
/// </remarks>
/// <param name="filename">The absolute path to the file which should be opened.</param>
/// <returns>Whether the file was successfully opened.</returns>
public abstract bool OpenFileExternally(string filename);
/// <summary>
/// Requests to present a file externally in the platform's native file browser.
/// </summary>
/// <remarks>
/// This will open the parent folder and, (if available) highlight the file.
/// Some platforms do not support interacting with files externally (ie. mobile or sandboxed platforms), check the return value as to whether it succeeded.
/// </remarks>
/// <example>
/// <para>"C:\Windows\explorer.exe" -> opens 'C:\Windows' and highlights 'explorer.exe' in the window.</para>
/// <para>"C:\Windows\System32" -> opens 'C:\Windows' and highlights 'System32' in the window.</para>
/// <para>"C:\Windows\System32\" -> opens 'C:\Windows\System32' and highlights nothing.</para>
/// </example>
/// <param name="filename">The absolute path to the file/folder to be shown in its parent folder.</param>
/// <returns>Whether the file was successfully presented.</returns>
public abstract bool PresentFileExternally(string filename);
/// <summary>
/// Requests that a URL be opened externally in a web browser, if available.
/// </summary>
/// <param name="url">The URL of the page which should be opened.</param>
public abstract void OpenUrlExternally(string url);
/// <summary>
/// Creates the game window for the host. Should be implemented per-platform if required.
/// </summary>
protected virtual IWindow CreateWindow(GraphicsSurfaceType preferredSurface) => null;
[CanBeNull]
public virtual Clipboard GetClipboard() => null;
protected virtual ReadableKeyCombinationProvider CreateReadableKeyCombinationProvider() => new ReadableKeyCombinationProvider();
private ReadableKeyCombinationProvider readableKeyCombinationProvider;
/// <summary>
/// The default initial path when requesting a user to select a file/folder.
/// </summary>
/// <remarks>
/// Provides a sane starting point for user-accessible storage.
/// </remarks>
public virtual string InitialFileSelectorPath => Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
/// <summary>
/// Retrieve a storage for the specified location.
/// </summary>
/// <param name="path">The absolute path to be used as a root for the storage.</param>
public abstract Storage GetStorage(string path);
/// <summary>
/// All valid user storage paths in order of usage priority.
/// </summary>
public virtual IEnumerable<string> UserStoragePaths => Environment.GetFolderPath(Environment.SpecialFolder.Personal).Yield();
/// <summary>
/// The main storage as proposed by the host game.
/// </summary>
public Storage Storage { get; protected set; }
/// <summary>
/// An auxiliary cache storage which is fixed in the default game directory.
/// </summary>
public Storage CacheStorage { get; protected set; }
/// <summary>
/// If caps-lock is enabled on the system, false if not overwritten by a subclass
/// </summary>
public virtual bool CapsLockEnabled => false;
public IEnumerable<GameThread> Threads => threadRunner.Threads;
/// <summary>
/// Register a thread to be monitored and tracked by this <see cref="GameHost"/>
/// </summary>
/// <param name="thread">The thread.</param>
public void RegisterThread(GameThread thread)
{
threadRunner.AddThread(thread);
thread.IsActive.BindTo(IsActive);
thread.UnhandledException = unhandledExceptionHandler;
if (thread.Monitor != null)
thread.Monitor.EnablePerformanceProfiling = PerformanceLogging.Value;
}
/// <summary>
/// Unregister a previously registered thread.<see cref="GameHost"/>
/// </summary>
/// <param name="thread">The thread.</param>
public void UnregisterThread(GameThread thread)
{
threadRunner.RemoveThread(thread);
IsActive.UnbindFrom(thread.IsActive);
thread.UnhandledException = null;
}
public DrawThread DrawThread { get; private set; }
public GameThread UpdateThread { get; private set; }
public InputThread InputThread { get; private set; }
public AudioThread AudioThread { get; private set; }
private double maximumUpdateHz;
/// <summary>
/// The target number of update frames per second when the game window is active.
/// </summary>
/// <remarks>
/// A value of 0 is treated the same as "unlimited" or <see cref="double.MaxValue"/>.
/// </remarks>
public double MaximumUpdateHz
{
get => maximumUpdateHz;
set => threadRunner.MaximumUpdateHz = UpdateThread.ActiveHz = maximumUpdateHz = value;
}
private double maximumDrawHz;
/// <summary>
/// The target number of draw frames per second when the game window is active.
/// </summary>
/// <remarks>
/// A value of 0 is treated the same as "unlimited" or <see cref="double.MaxValue"/>.
/// </remarks>
public double MaximumDrawHz
{
get => maximumDrawHz;
set => DrawThread.ActiveHz = maximumDrawHz = value;
}
/// <summary>
/// The target number of updates per second when the game window is inactive.
/// This is applied to all threads.
/// </summary>
/// <remarks>
/// A value of 0 is treated the same as "unlimited" or <see cref="double.MaxValue"/>.
/// </remarks>
public double MaximumInactiveHz
{
get => DrawThread.InactiveHz;
set
{
DrawThread.InactiveHz = value;
threadRunner.MaximumInactiveHz = UpdateThread.InactiveHz = value;
}
}
private PerformanceMonitor inputMonitor => InputThread.Monitor;
private PerformanceMonitor drawMonitor => DrawThread.Monitor;
private readonly Lazy<string> fullPathBacking = new Lazy<string>(RuntimeInfo.GetFrameworkAssemblyPath);
public string FullPath => fullPathBacking.Value;
/// <summary>
/// The name of the game to be hosted.
/// </summary>
public string Name { get; }
[NotNull]
public HostOptions Options { get; private set; }
public DependencyContainer Dependencies { get; } = new DependencyContainer();
private bool suspended;
protected GameHost([NotNull] string gameName, [CanBeNull] HostOptions options = null)
{
Options = options ?? new HostOptions();
Name = gameName;
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new Vector2Converter() }
};
}
protected virtual IRenderer CreateRenderer() => new GLRenderer();
/// <summary>
/// Performs a GC collection and frees all framework caches.
/// This is a blocking call and should not be invoked during periods of user activity unless memory is critical.
/// </summary>
public void Collect()
{
SixLabors.ImageSharp.Configuration.Default.MemoryAllocator.ReleaseRetainedResources();
GC.Collect();
}
private void unhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
var exception = (Exception)args.ExceptionObject;
logException(exception, "unhandled");
abortExecutionFromException(sender, exception, args.IsTerminating);
}
private void unobservedExceptionHandler(object sender, UnobservedTaskExceptionEventArgs args)
{
var actualException = args.Exception.AsSingular();
// unobserved exceptions are logged but left unhandled (most of the time they are not intended to be critical).
logException(actualException, "unobserved");
if (DebugUtils.IsNUnitRunning)
abortExecutionFromException(sender, actualException, false);
}
private void logException(Exception exception, string type)
{
Logger.Error(exception, $"An {type} error has occurred.", recursive: true);
}
/// <summary>
/// Give the running application a last change to handle an otherwise unhandled exception, and potentially ignore it.
/// </summary>
/// <param name="sender">The source, generally a <see cref="GameThread"/>.</param>
/// <param name="exception">The unhandled exception.</param>
/// <param name="isTerminating">Whether the CLR is terminating.</param>
private void abortExecutionFromException(object sender, Exception exception, bool isTerminating)
{
// nothing needs to be done if the consumer has requested continuing execution.
if (ExceptionThrown?.Invoke(exception) == true) return;
// otherwise, we need to unwind and abort execution.
AppDomain.CurrentDomain.UnhandledException -= unhandledExceptionHandler;
TaskScheduler.UnobservedTaskException -= unobservedExceptionHandler;
// In the case of an unhandled exception, it's feasible that the disposal flow for `GameHost` doesn't run.
// This can result in the exception not being logged (or being partially logged) due to the logger running asynchronously.
// We force flushing the logger here to ensure logging completes.
Logger.Flush();
var captured = ExceptionDispatchInfo.Capture(exception);
var thrownEvent = new ManualResetEventSlim(false);
//we want to throw this exception on the input thread to interrupt window and also headless execution.
InputThread.Scheduler.Add(() =>
{
try
{
captured.Throw();
}
finally
{
thrownEvent.Set();
}
});
// Stopping running threads before the exception is rethrown on the input thread causes some debuggers (e.g. Rider 2020.2) to not properly display the stack.
// To avoid this, pause the exceptioning thread until the rethrow takes place.
waitForThrow();
void waitForThrow()
{
// This is bypassed for sources in a few situations where deadlocks can occur:
// 1. When the exceptioning thread is GameThread.Input.
// 2. When the game is running in single-threaded mode. Single threaded stacks will be displayed correctly at the point of rethrow.
// 3. When the CLR is terminating. We can't guarantee the input thread is still running, and may delay application termination.
if (isTerminating || (sender is GameThread && (sender == InputThread || executionMode.Value == ExecutionMode.SingleThread)))
return;
// The process can deadlock in an extreme case such as the input thread dying before the delegate executes, so wait up to a maximum of 10 seconds at all times.
thrownEvent.Wait(TimeSpan.FromSeconds(10));
}
}
protected virtual void OnActivated() => UpdateThread.Scheduler.Add(() => Activated?.Invoke());
protected virtual void OnDeactivated() => UpdateThread.Scheduler.Add(() => Deactivated?.Invoke());
protected void OnExitRequested() => UpdateThread.Scheduler.Add(() => ExitRequested?.Invoke());
protected virtual void OnExited()
{
Exited?.Invoke();
}
protected TripleBuffer<DrawNode> DrawRoots = new TripleBuffer<DrawNode>();
protected Container Root;
private ulong frameCount;
protected virtual void UpdateFrame()
{
if (Root == null) return;
frameCount++;
if (Window == null)
{
var windowedSize = Config.Get<Size>(FrameworkSetting.WindowedSize);
Root.Size = new Vector2(windowedSize.Width, windowedSize.Height);
}
else if (Window.WindowState != WindowState.Minimised)
Root.Size = new Vector2(Window.ClientSize.Width, Window.ClientSize.Height);
// Ensure we maintain a valid size for any children immediately scaling by the window size
Root.Size = Vector2.ComponentMax(Vector2.One, Root.Size);
TypePerformanceMonitor.NewFrame();
Root.UpdateSubTree();
Root.UpdateSubTreeMasking(Root, Root.ScreenSpaceDrawQuad.AABBFloat);
using (var buffer = DrawRoots.GetForWrite())
buffer.Object = Root.GenerateDrawNodeSubtree(frameCount, buffer.Index, false);
}
private readonly DepthValue depthValue = new DepthValue();
protected virtual void DrawFrame()
{
if (Root == null)
return;
if (ExecutionState != ExecutionState.Running)
return;
ObjectUsage<DrawNode> buffer;
using (drawMonitor.BeginCollecting(PerformanceCollectionType.Sleep))
buffer = DrawRoots.GetForRead();
if (buffer == null)
return;
try
{
using (drawMonitor.BeginCollecting(PerformanceCollectionType.DrawReset))
Renderer.BeginFrame(new Vector2(Window.ClientSize.Width, Window.ClientSize.Height));
if (!bypassFrontToBackPass.Value)
{
depthValue.Reset();
Renderer.SetBlend(BlendingParameters.None);
Renderer.SetBlendMask(BlendingMask.None);
Renderer.PushDepthInfo(DepthInfo.Default);
// Front pass
buffer.Object.DrawOpaqueInteriorSubTree(Renderer, depthValue);
Renderer.PopDepthInfo();
Renderer.SetBlendMask(BlendingMask.All);
// The back pass doesn't write depth, but needs to depth test properly
Renderer.PushDepthInfo(new DepthInfo(true, false));
}
else
{
// Disable depth testing
Renderer.PushDepthInfo(new DepthInfo(false, false));
}
// Back pass
buffer.Object.Draw(Renderer);
Renderer.PopDepthInfo();
Renderer.FinishFrame();
using (drawMonitor.BeginCollecting(PerformanceCollectionType.SwapBuffer))
Swap();
Window.OnDraw();
}
finally
{
buffer.Dispose();
}
}
/// <summary>
/// Swap the buffers.
/// </summary>
protected virtual void Swap()
{
Renderer.SwapBuffers();
if (Window.GraphicsSurface.Type == GraphicsSurfaceType.OpenGL && Renderer.VerticalSync)
// without waiting (i.e. glFinish), vsync is basically unplayable due to the extra latency introduced.
// we will likely want to give the user control over this in the future as an advanced setting.
Renderer.WaitUntilIdle();
}
/// <summary>
/// Takes a screenshot of the game. The returned <see cref="Image{TPixel}"/> must be disposed by the caller when applicable.
/// </summary>
/// <returns>The screenshot as an <see cref="Image{TPixel}"/>.</returns>
public async Task<Image<Rgba32>> TakeScreenshotAsync()
{
if (Window == null) throw new InvalidOperationException($"{nameof(Window)} has not been set!");
using (var completionEvent = new ManualResetEventSlim(false))
{
int width = Window.ClientSize.Width;
int height = Window.ClientSize.Height;
var pixelData = SixLabors.ImageSharp.Configuration.Default.MemoryAllocator.Allocate<Rgba32>(width * height);
DrawThread.Scheduler.Add(() =>
{
Renderer.MakeCurrent();
GL.ReadPixels(0, 0, width, height, PixelFormat.Rgba, PixelType.UnsignedByte, ref MemoryMarshal.GetReference(pixelData.Memory.Span));
// ReSharper disable once AccessToDisposedClosure
completionEvent.Set();
});
// this is required as attempting to use a TaskCompletionSource blocks the thread calling SetResult on some configurations.
// ReSharper disable once AccessToDisposedClosure
if (!await Task.Run(() => completionEvent.Wait(5000)).ConfigureAwait(false))
throw new TimeoutException("Screenshot data did not arrive in a timely fashion");
var image = Image.LoadPixelData<Rgba32>(pixelData.Memory.Span, width, height);
image.Mutate(c => c.Flip(FlipMode.Vertical));
return image;
}
}
public ExecutionState ExecutionState
{
get => executionState;
private set
{
if (executionState == value)
return;
executionState = value;
Logger.Log($"Host execution state changed to {value}");
}
}
private ExecutionState executionState;
/// <summary>
/// Schedules the game to exit in the next frame.
/// </summary>
/// <remarks>Consider using <see cref="SuspendToBackground"/> on mobile platforms that can't exit normally.</remarks>
public void Exit()
{
if (CanExit)
PerformExit(false);
}
/// <summary>
/// Suspends and minimizes the game to background.
/// </summary>
/// <remarks>
/// This is provided as an alternative to <see cref="Exit"/> on hosts that can't exit (see <see cref="CanExit"/>).
/// Should only be called if <see cref="CanSuspendToBackground"/> is <c>true</c>.
/// </remarks>
/// <returns><c>true</c> if the game was successfully suspended and minimized.</returns>
public virtual bool SuspendToBackground()
{
return false;
}
/// <summary>
/// Schedules the game to exit in the next frame (or immediately if <paramref name="immediately"/> is true).
/// </summary>
/// <remarks>
/// Will never be called if <see cref="CanExit"/> is <see langword="false"/>.
/// </remarks>
/// <param name="immediately">If true, exits the game immediately. If false (default), schedules the game to exit in the next frame.</param>
protected virtual void PerformExit(bool immediately) => performExit(immediately);
private void performExit(bool immediately)
{
if (executionState == ExecutionState.Stopped || executionState == ExecutionState.Idle)
return;
ExecutionState = ExecutionState.Stopping;
if (immediately)
exit();
else
InputThread.Scheduler.Add(exit, false);
void exit()
{
Debug.Assert(ExecutionState == ExecutionState.Stopping);
Window?.Close();
threadRunner.Stop();
ExecutionState = ExecutionState.Stopped;
stoppedEvent.Set();
}
}
private static readonly SemaphoreSlim host_running_mutex = new SemaphoreSlim(1);
public void Run(Game game)
{
if (Thread.CurrentThread.IsThreadPoolThread)
{
// This is a common misuse of GameHost, where typically consumers will have a mutex waiting for the game to run.
// Exceptions thrown here will become unobserved, so any such mutexes will never be set.
// Instead, immediately terminate the application in order to notify of incorrect use in all cases.
Environment.FailFast($"{nameof(GameHost)}s should not be run on a TPL thread (use TaskCreationOptions.LongRunning).");
}
if (RuntimeInfo.IsDesktop)
{
// Mono (netcore) throws for this property
GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
}
if (ExecutionState != ExecutionState.Idle)
throw new InvalidOperationException("A game that has already been run cannot be restarted.");
Renderer = CreateRenderer();
try
{
if (!host_running_mutex.Wait(10000))
throw new TimeoutException($"This {nameof(GameHost)} could not start {game} because another {nameof(GameHost)} was already running.");
threadRunner = CreateThreadRunner(InputThread = new InputThread());
AppDomain.CurrentDomain.UnhandledException += unhandledExceptionHandler;
TaskScheduler.UnobservedTaskException += unobservedExceptionHandler;
RegisterThread(InputThread);
RegisterThread(AudioThread = new AudioThread());
RegisterThread(UpdateThread = new UpdateThread(UpdateFrame, DrawThread)
{
Monitor = { HandleGC = true },
});
RegisterThread(DrawThread = new DrawThread(DrawFrame, this));
Trace.Listeners.Clear();
Trace.Listeners.Add(new ThrowingTraceListener());
var assembly = DebugUtils.GetEntryAssembly();
Logger.GameIdentifier = Name;
Logger.VersionIdentifier = assembly.GetName().Version?.ToString() ?? Logger.VersionIdentifier;
Dependencies.CacheAs(this);
Dependencies.CacheAs(Storage = game.CreateStorage(this, GetDefaultGameStorage()));
Dependencies.CacheAs(Renderer);
CacheStorage = GetDefaultGameStorage().GetStorageForDirectory("cache");
SetupForRun();
Window = CreateWindow(GraphicsSurfaceType.OpenGL);
populateInputHandlers();
SetupConfig(game.GetFrameworkConfigDefaults() ?? new Dictionary<FrameworkSetting, object>());
initialiseInputHandlers();
if (Window != null)
{
Window.SetupWindow(Config);
Window.Create();
Window.Title = $@"osu!framework (running ""{Name}"")";
Renderer.Initialise(Window.GraphicsSurface);
currentDisplayMode = Window.CurrentDisplayMode.GetBoundCopy();
currentDisplayMode.BindValueChanged(_ => updateFrameSyncMode());
IsActive.BindTo(Window.IsActive);
}
Dependencies.CacheAs(readableKeyCombinationProvider = CreateReadableKeyCombinationProvider());
Dependencies.CacheAs(CreateTextInput());
ExecutionState = ExecutionState.Running;
threadRunner.Start();
DrawThread.WaitUntilInitialized();
bootstrapSceneGraph(game);
frameSyncMode.TriggerChange();
IsActive.BindValueChanged(active =>
{
if (active.NewValue)
OnActivated();
else
OnDeactivated();
}, true);
try
{
if (Window != null)
{
switch (Window)
{
case SDL2DesktopWindow window:
window.Update += windowUpdate;
break;
case OsuTKWindow tkWindow:
tkWindow.UpdateFrame += (_, _) => windowUpdate();
break;
}
Window.ExitRequested += OnExitRequested;
Window.Exited += OnExited;
Window.KeymapChanged += readableKeyCombinationProvider.OnKeymapChanged;
//we need to ensure all threads have stopped before the window is closed (mainly the draw thread
//to avoid GL operations running post-cleanup).
Window.Exited += threadRunner.Stop;
Window.Run();
}
else
{
while (ExecutionState != ExecutionState.Stopped)
windowUpdate();
}
}
catch (OutOfMemoryException)
{
}
}
finally
{
if (CanExit)
{
// Close the window and stop all threads
performExit(true);
host_running_mutex.Release();
}
}
}
/// <summary>
/// Finds the default <see cref="Storage"/> for the game to be used if <see cref="Game.CreateStorage"/> is not overridden.
/// </summary>
/// <returns>The <see cref="Storage"/>.</returns>
protected virtual Storage GetDefaultGameStorage()
{
// first check all valid paths for any existing install.
foreach (string path in UserStoragePaths)
{
var storage = GetStorage(path);
// if an existing data directory exists for this application, prefer it immediately.
if (storage.ExistsDirectory(Name))
return storage.GetStorageForDirectory(Name);
}
// if an existing directory could not be found, use the first path that can be created.
foreach (string path in UserStoragePaths)
{
try
{
return GetStorage(path).GetStorageForDirectory(Name);
}
catch
{
// may fail on directory creation.
}
}
throw new InvalidOperationException("No valid user storage path could be resolved.");
}
/// <summary>
/// Pauses all active threads. Call <see cref="Resume"/> to resume execution.
/// </summary>
public void Suspend()
{
suspended = true;
threadRunner.Suspend();
}
/// <summary>
/// Resumes all of the current paused threads after <see cref="Suspend"/> was called.
/// </summary>
public void Resume()
{
threadRunner.Start();
suspended = false;
}
private ThreadRunner threadRunner;
private void windowUpdate()
{
inputPerformanceCollectionPeriod?.Dispose();
inputPerformanceCollectionPeriod = null;
if (suspended)
return;
threadRunner.RunMainLoop();
inputPerformanceCollectionPeriod = inputMonitor.BeginCollecting(PerformanceCollectionType.WndProc);
}
/// <summary>
/// Prepare this game host for <see cref="Run"/>.
/// <remarks>
/// <see cref="Storage"/> is available here.
/// </remarks>
/// </summary>
protected virtual void SetupForRun()
{
Logger.Storage = Storage.GetStorageForDirectory("logs");
Logger.Enabled = true;
}
private void populateInputHandlers()
{
AvailableInputHandlers = CreateAvailableInputHandlers().ToImmutableArray();
}
private void initialiseInputHandlers()
{
foreach (var handler in AvailableInputHandlers)
{
if (!handler.Initialize(this))
handler.Enabled.Value = false;
}
}
/// <summary>
/// Reset all input handlers' settings to a default state.
/// </summary>
public void ResetInputHandlers()
{
// restore any disable handlers per legacy configuration.
ignoredInputHandlers.TriggerChange();
foreach (var handler in AvailableInputHandlers)
{
handler.Reset();
}
}
/// <summary>
/// The clock which is to be used by the scene graph (will be assigned to <see cref="Root"/>).
/// </summary>
protected virtual IFrameBasedClock SceneGraphClock => UpdateThread.Clock;
private void bootstrapSceneGraph(Game game)
{
var root = game.CreateUserInputManager();
root.Child = new PlatformActionContainer
{
Child = new FrameworkActionContainer
{
Child = new SafeAreaDefiningContainer
{
RelativeSizeAxes = Axes.Both,
Child = game
}
}
};
Dependencies.Cache(root);
Dependencies.CacheAs(game);
game.SetHost(this);
root.Load(SceneGraphClock, Dependencies);
//publish bootstrapped scene graph to all threads.
Root = root;
}
private InvokeOnDisposal inputPerformanceCollectionPeriod;
private Bindable<bool> bypassFrontToBackPass;
private Bindable<FrameSync> frameSyncMode;
private IBindable<DisplayMode> currentDisplayMode;
private Bindable<string> ignoredInputHandlers;
private readonly Bindable<double> cursorSensitivity = new Bindable<double>(1);
public readonly Bindable<bool> PerformanceLogging = new Bindable<bool>();
private Bindable<WindowMode> windowMode;
private Bindable<ExecutionMode> executionMode;
private Bindable<string> threadLocale;
protected virtual void SetupConfig(IDictionary<FrameworkSetting, object> defaultOverrides)
{
if (!defaultOverrides.ContainsKey(FrameworkSetting.WindowMode))
defaultOverrides.Add(FrameworkSetting.WindowMode, Window?.DefaultWindowMode ?? WindowMode.Windowed);
Dependencies.Cache(DebugConfig = new FrameworkDebugConfigManager());
Dependencies.Cache(Config = new FrameworkConfigManager(Storage, defaultOverrides));
windowMode = Config.GetBindable<WindowMode>(FrameworkSetting.WindowMode);
windowMode.BindValueChanged(mode =>
{
if (Window == null)
return;
if (!Window.SupportedWindowModes.Contains(mode.NewValue))
windowMode.Value = Window.DefaultWindowMode;
}, true);
executionMode = Config.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
executionMode.BindValueChanged(e => threadRunner.ExecutionMode = e.NewValue, true);
frameSyncMode = Config.GetBindable<FrameSync>(FrameworkSetting.FrameSync);
frameSyncMode.ValueChanged += _ => updateFrameSyncMode();
#pragma warning disable 618
// pragma region can be removed 20210911
ignoredInputHandlers = Config.GetBindable<string>(FrameworkSetting.IgnoredInputHandlers);
ignoredInputHandlers.ValueChanged += e =>
{
var configIgnores = e.NewValue.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
foreach (var handler in AvailableInputHandlers)
{
string handlerType = handler.ToString();
handler.Enabled.Value = configIgnores.All(ch => ch != handlerType);
}
};
Config.BindWith(FrameworkSetting.CursorSensitivity, cursorSensitivity);
var cursorSensitivityHandlers = AvailableInputHandlers.OfType<IHasCursorSensitivity>();
// one way bindings to preserve compatibility.
cursorSensitivity.BindValueChanged(val =>
{
foreach (var h in cursorSensitivityHandlers)
h.Sensitivity.Value = val.NewValue;
}, true);