35public sealed class Engine : IDisposable
37 #region static members
39 private static readonly Lazy<Engine> _instance =
new(() =>
new Engine());
49 public static Engine
Instance => _instance.Value;
59 public static ILogger<Engine>
Logger => EngineLogger.GetLogger<Engine>();
63 #region private fields
65 private long _startTick;
66 private long _lastCPSSamplingTick;
67 private long _lastBackgroundTick = HighResTimer.GetCurrentTick();
68 private long _lastForegroundTick = HighResTimer.GetCurrentTick();
69 private long _lastCycleTick = HighResTimer.GetCurrentTick();
70 private readonly FixedStepAccumulator _timerDrivenSteps =
new();
71 private long _timerDrivenForegroundAccumulatedTicks;
72 private long _lastTimerDrivenForegroundDriverTick;
73 private int _timerDrivenForegroundTargetFps;
74 private bool _isTimerDriven;
76 private long _grossCyclesThisMeasure = 0;
77 private long _netCyclesThisMeasure = 0;
78 private double _grossCPS = 0;
79 private double _netFPS = 0;
81 private Task? _cycleTask;
83 private bool _deferredDisposeScheduled;
85 #endregion private fields
211 "Legacy CPS/FPS notifications are deprecated. Use Engine.Profiler for runtime telemetry; ProfilerWidget provides an optional in-game display.",
212 DiagnosticId =
"GOND0001")]
245 _engineTelemetry =
Profiler.RegisterSource(
"Engine",
"Core")!;
246 _engineTelemetry.Define(
"cycle.cpu.ms");
247 _engineTelemetry.Define(
"background.cpu.ms");
248 _engineTelemetry.Define(
"foreground.cpu.ms");
251 private volatile bool _isInitialized =
false;
252 private volatile bool _isInitializing =
false;
253 private readonly ManualResetEventSlim _initDone =
new(
false);
311 string? configFileName =
null,
312 bool? autoSaveConfig =
null,
316 IGamepadManager<IGamepadAdapter>? gamepadManager =
null)
324 configurationStore:
null);
339 bool? autoSaveConfig =
null,
343 IGamepadManager<IGamepadAdapter>? gamepadManager =
null)
345 ArgumentNullException.ThrowIfNull(configurationStore);
348 configFileName:
null,
357 private void InitializeCore(
358 string? configFileName,
359 bool? autoSaveConfig,
363 IGamepadManager<IGamepadAdapter>? gamepadManager,
366 if (_isInitialized || _isInitializing)
372 _isInitializing =
true;
383 _configurationStore?.Dispose();
387 Logger.LogError(ex,
"Error saving the engine configuration during initialization.");
390 _configurationStore = configurationStore ?? EngineConfigurationFile.Load(configFileName, autoSaveConfig);
392 if (configurationStore is not
null && autoSaveConfig.HasValue)
393 _configurationStore.AutoSave = autoSaveConfig.Value;
403 EngineState.MergeFromFile(
405 stateFile.IsCompressed,
406 stateFile.OverwriteExisting,
407 stateFile.EngineStateParts);
411 if (keyboardAdapter !=
null)
412 KeyboardEventPoller.Initialize(keyboardAdapter);
414 if (mouseAdapter !=
null)
415 MouseEventPoller.Initialize(mouseAdapter);
417 if (touchAdapter !=
null)
418 Input.TouchAdapter = touchAdapter;
420 if (gamepadManager is not
null)
421 Input.GamepadManager = gamepadManager;
428 EnginePluginRegistry.InvokeInitialize(
this);
430 _isInitialized =
true;
439 _isInitializing =
false;
452 var store = _configurationStore
453 ??
throw new InvalidOperationException(
"The engine has no initialized configuration store.");
481 if (SynchronizationContext.Current ==
null)
482 throw new InvalidOperationException(
"SynchronizationContext cannot be null.");
484 Start(SynchronizationContext.Current);
529 public void Start(SynchronizationContext uiContext)
540 var initializationWaitTimeoutSeconds =
Configuration.StartInitializationWaitTimeout;
541 var initializationWaitTimeout = TimeSpan.FromSeconds(initializationWaitTimeoutSeconds);
543 if (!_initDone.Wait(initializationWaitTimeout))
544 throw new InvalidOperationException(
545 $
"Engine initialization did not complete within {initializationWaitTimeoutSeconds:0.###} seconds.");
548 throw new InvalidOperationException(
549 "Engine initialization failed on another thread. Call Initialize() again and resolve the initialization error.");
557 throw new InvalidOperationException(
"Engine failed to initialize.");
560 _isTimerDriven =
false;
561 EngineSimulationClock.UseWallClock();
564 _startTick = HighResTimer.GetCurrentTick();
565 _lastCPSSamplingTick = _startTick;
566 _lastCycleTick = _startTick;
568 _cycleTask = Task.Run(() =>
623 throw new InvalidOperationException(
624 "Engine initialization is already in progress on another thread. " +
625 "Blocking waits are not supported in timer-driven (single-threaded) mode.");
633 _startTick = HighResTimer.GetCurrentTick();
634 _lastCPSSamplingTick = _startTick;
635 _lastCycleTick = _startTick;
636 _lastBackgroundTick = _startTick;
637 _lastForegroundTick = _startTick;
638 _timerDrivenSteps.Reset(_startTick);
639 _timerDrivenForegroundAccumulatedTicks = 0;
640 _lastTimerDrivenForegroundDriverTick = _startTick;
642 EngineSimulationClock.BeginTimerDriven(_startTick);
644 _isTimerDriven =
true;
680 lock (RenderStateSynchronization.SyncRoot)
684 long driverTick = HighResTimer.GetCurrentTick();
686 var batch = _timerDrivenSteps.Advance(
691 bool render = IsTimerDrivenForegroundDue(driverTick);
692 double frameDelta = HighResTimer.GetDuration(_lastForegroundTick, driverTick);
694 if (batch.StepCount == 0)
697 RenderFrame(driverTick, frameDelta);
700 CalculateCPS(driverTick);
705 double fixedDelta = batch.StepTicks / (double)HighResTimer.TicksPerSecond;
707 for (
int step = 0; step < batch.StepCount &&
IsRunning; step++)
709 long simulationTick = batch.GetStepTick(step);
710 EngineSimulationClock.SetTimerDrivenTick(simulationTick);
712 bool isLastStep = step == batch.StepCount - 1;
717 render && isLastStep,
720 sampleCps: isLastStep);
757 _isTimerDriven =
false;
758 EngineSimulationClock.UseWallClock();
759 InvokeShutdownAfterCycleStops();
775 var cycleTask = _cycleTask;
777 if (cycleTask is not
null && !cycleTask.IsCompleted &&
EngineDispatcher.IsOnEngineThread)
778 throw new InvalidOperationException(
"StopAndWait must be called outside the background engine thread.");
781 cycleTask?.GetAwaiter().GetResult();
784 private void InvokeShutdownAfterCycleStops()
786 var cycleTask = _cycleTask;
788 if (cycleTask is not
null && !cycleTask.IsCompleted)
790 cycleTask.ContinueWith(
791 _ => EnginePluginRegistry.InvokeShutdown(
this),
792 System.Threading.CancellationToken.None,
793 System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously,
794 System.Threading.Tasks.TaskScheduler.Default);
799 EnginePluginRegistry.InvokeShutdown(
this);
802 #region public properties
894 "Legacy CPS/FPS properties are deprecated. Use Engine.Profiler for runtime telemetry; ProfilerWidget provides an optional in-game display.",
895 DiagnosticId =
"GOND0001")]
913 "Legacy CPS/FPS properties are deprecated. Use Engine.Profiler for runtime telemetry; ProfilerWidget provides an optional in-game display.",
914 DiagnosticId =
"GOND0001")]
953 get => Volatile.Read(ref _config!);
954 private set => Volatile.Write(ref _config, value);
1014 #endregion public properties
1016 #region private methods
1018 private void Cycle()
1023 RenderStateSynchronization.WaitForPendingGpuRenderers();
1025 lock (RenderStateSynchronization.SyncRoot)
1029 long tick = HighResTimer.GetCurrentTick();
1030 var deltaSeconds = HighResTimer.GetDuration(_lastCycleTick, tick);
1031 _lastCycleTick = tick;
1036 IsForegroundDue(tick),
1043 private void RunSimulationCycle(
1044 long simulationTick,
1045 double simulationDelta,
1056 long telemetryGeneration = _engineTelemetry.BeginSample();
1057 long telemetryStarted = telemetryGeneration == 0 ? 0 : HighResTimer.GetCurrentTick();
1059 EnginePluginRegistry.InvokePreCycle(
this, simulationDelta);
1061 DoBackgroundTasks(simulationTick);
1064 RenderFrame(renderTick, frameDelta);
1066 _grossCyclesThisMeasure++;
1069 CalculateCPS(renderTick);
1071 EnginePluginRegistry.InvokePostCycle(
this, simulationDelta);
1073 if (telemetryGeneration != 0)
1074 _engineTelemetry.Record(
1075 telemetryGeneration,
1077 HighResTimer.GetDuration(telemetryStarted, HighResTimer.GetCurrentTick()) * 1000d);
1080 private bool IsForegroundDue(
long tick) =>
1081 Configuration.TargetFPS <= 0
1082 || (tick - _lastForegroundTick) >= HighResTimer.TicksPerSecond /
Configuration.TargetFPS;
1084 private bool IsTimerDrivenForegroundDue(
long tick)
1087 long elapsedTicks = Math.Max(0, tick - _lastTimerDrivenForegroundDriverTick);
1088 _lastTimerDrivenForegroundDriverTick = tick;
1092 _timerDrivenForegroundAccumulatedTicks = 0;
1093 _timerDrivenForegroundTargetFps = targetFps;
1097 if (_timerDrivenForegroundTargetFps != targetFps)
1099 _timerDrivenForegroundTargetFps = targetFps;
1100 _timerDrivenForegroundAccumulatedTicks = 0;
1103 _timerDrivenForegroundAccumulatedTicks += elapsedTicks;
1105 long frameIntervalTicks = Math.Max(1, HighResTimer.TicksPerSecond / targetFps);
1107 if (_timerDrivenForegroundAccumulatedTicks < frameIntervalTicks)
1114 _timerDrivenForegroundAccumulatedTicks %= frameIntervalTicks;
1118 private void RenderFrame(
long tick,
double delta)
1120 long telemetryGeneration = _engineTelemetry.BeginSample();
1121 long telemetryStarted = telemetryGeneration == 0 ? 0 : HighResTimer.GetCurrentTick();
1122 EnginePluginRegistry.InvokePreFrameRender(
this, delta);
1124 DoForegroundTasks(tick);
1126 EnginePluginRegistry.InvokePostFrameRender(
this, delta);
1128 _lastForegroundTick = tick;
1129 _netCyclesThisMeasure++;
1131 if (telemetryGeneration != 0)
1132 _engineTelemetry.Record(
1133 telemetryGeneration,
1134 "foreground.cpu.ms",
1135 HighResTimer.GetDuration(telemetryStarted, HighResTimer.GetCurrentTick()) * 1000d);
1138 private void DoBackgroundTasks(
long tick)
1140 long telemetryGeneration = _engineTelemetry.BeginSample();
1141 long telemetryStarted = telemetryGeneration == 0 ? 0 : HighResTimer.GetCurrentTick();
1143 var deltaSeconds = HighResTimer.GetDuration(_lastBackgroundTick, tick);
1148 Timer.RaiseTimerEvents(
TimerType.PreCycle, tick);
1151 KeyboardEventPoller.Instance?.PollForEvents(tick);
1154 MouseEventPoller.Instance?.PollForEvents(tick);
1157 TouchEventPoller.Instance?.PollForEvents(tick);
1160 GamepadEventPoller.Instance?.PollForEvents(tick);
1163 for (
int i = 0; i < Tile.TilesAnimating.Count; i++)
1164 Tile.TilesAnimating[i].TileAnimator.CycleAnimation(tick);
1167 SpriteManager.Instance.MoveSprites(tick);
1170 foreach (var scene
in Scenes.Scene.GetAllScenes())
1172 foreach (var layer
in scene.SceneLayers)
1173 layer.CollisionResolver.Resolve();
1177 foreach (var surface
in RenderSurfaceHostRegistry.All)
1178 surface.ViewManager.UpdateCameras(deltaSeconds);
1182 _lastBackgroundTick = tick;
1184 if (telemetryGeneration != 0)
1185 _engineTelemetry.Record(
1186 telemetryGeneration,
1187 "background.cpu.ms",
1188 HighResTimer.GetDuration(telemetryStarted, HighResTimer.GetCurrentTick()) * 1000d);
1191 private void DoForegroundTasks(
long tick)
1197 foreach (var surface
in RenderSurfaceHostRegistry.All)
1198 surface.Effects.Update(tick);
1201 DirectDrawingManager.Instance.UpdateAll(tick);
1204 foreach (var surface
in RenderSurfaceHostRegistry.All)
1205 surface.ProduceRenderFrameSnapshot(tick);
1208 foreach (var surface
in RenderSurfaceHostRegistry.All)
1209 if (!surface.Backbuffer.IsGlThreadRendered)
1210 surface.RenderToBackbuffer(tick);
1213 foreach (var surface
in RenderSurfaceHostRegistry.All)
1214 if (!surface.Backbuffer.IsGlThreadRendered)
1215 surface.PresentBackbufferToAdapter();
1222 Timer.RaiseTimerEvents(
TimerType.PostCycle, tick);
1225 private void CalculateCPS(
long tick)
1228 long elapsedTicks = tick - _lastCPSSamplingTick;
1234 long grossCycles = _grossCyclesThisMeasure;
1235 long netCycles = _netCyclesThisMeasure;
1238 double elapsedSec = elapsedTicks / (double)HighResTimer.TicksPerSecond;
1239 double grossCps = grossCycles * HighResTimer.TicksPerSecond / (double)elapsedTicks;
1240 double netCps = netCycles * HighResTimer.TicksPerSecond / (double)elapsedTicks;
1243 long totalGpuFrames = 0;
1244 int gpuSurfaceCount = 0;
1246 foreach (var surface
in RenderSurfaceHostRegistry.All.ToArray())
1248 if (surface.Backbuffer is GpuBackbuffer gpuBb)
1250 totalGpuFrames += gpuBb.ConsumeFrameCount();
1255 double? gpuFps = gpuSurfaceCount > 0
1256 ? totalGpuFrames * HighResTimer.TicksPerSecond / (double)elapsedTicks
1260 var args =
new CyclesPerSecondCalculatedEventArgs(
1272 _grossCPS = grossCps;
1276 _lastCPSSamplingTick = tick;
1277 _grossCyclesThisMeasure = 0;
1278 _netCyclesThisMeasure = 0;
1281 private static void ConfigureLogging(EngineConfiguration configuration)
1286 EngineLogger.StopAsyncLogging(flush:
true);
1297 #endregion private methods
1299 #region IDisposable support
1301 private void Dispose(
bool disposing)
1317 catch (Exception ex)
1319 Logger.LogError(ex,
"Unhandled exception calling Stop()");
1325 var cycleTask = _cycleTask;
1327 if (cycleTask is not
null &&
EngineDispatcher.IsOnEngineThread && !cycleTask.IsCompleted)
1329 if (!_deferredDisposeScheduled)
1331 _deferredDisposeScheduled =
true;
1333 cycleTask.ContinueWith(
1334 _ => CompleteManagedDisposal(),
1335 System.Threading.CancellationToken.None,
1336 System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously,
1337 System.Threading.Tasks.TaskScheduler.Default);
1346 catch (Exception ex)
1348 Logger.LogError(ex,
"Error waiting for engine loop to exit.");
1351 CompleteManagedDisposal();
1361 private void CompleteManagedDisposal()
1375 Input.KeyboardEventPoller?.StopMonitoringAllKeys();
1376 MouseEventPoller.Reset();
1377 TouchEventPoller.Reset();
1379 if (
Input.GamepadManager is not
null)
1380 foreach (var gamepadAdapter
in Input.GamepadManager.ConnectedAdapters)
1381 Input.GamepadEventPoller?.StopMonitoringAllButtons(gamepadAdapter.GamepadId);
1385 _configurationStore?.Dispose();
1387 catch (Exception ex)
1389 Logger.LogError(ex,
"Error saving the engine configuration during disposal.");
1393 _configurationStore =
null;
1397 EngineLogger.StopAsyncLogging(flush:
Configuration.FlushAsyncLogsOnShutdown);
1412 private static void SafeInvoke(Action? evnt)
1418 catch (Exception ex)
1421 Logger.LogError(ex,
"Unhandled exception in disposal event handler.");
1450 GC.SuppressFinalize(
this);
1459 #endregion IDisposable support