LCOV - code coverage report
Current view: top level - src - main.cpp (source / functions) Coverage Total Hit
Test: coverage_filtered.info Lines: 58.9 % 214 126
Test Date: 2026-03-01 21:30:38 Functions: 75.0 % 4 3
Branches: 33.3 % 522 174

             Branch data     Line data    Source code
       1                 :             : #ifdef _WIN32
       2                 :             : #include <windows.h>
       3                 :             : #else
       4                 :             : #include <signal.h>
       5                 :             : #endif
       6                 :             : #include <iostream>
       7                 :             : #include <cmath>
       8                 :             : #include <algorithm>
       9                 :             : #include <thread>
      10                 :             : #include <chrono>
      11                 :             : 
      12                 :             : #include "FFBEngine.h"
      13                 :             : #include "GuiLayer.h"
      14                 :             : #include "Config.h"
      15                 :             : #include "DirectInputFFB.h"
      16                 :             : #include "GameConnector.h"
      17                 :             : #include "Version.h"
      18                 :             : #include "Logger.h"    // Added Logger
      19                 :             : #include "RateMonitor.h"
      20                 :             : #include "HealthMonitor.h"
      21                 :             : #include <optional>
      22                 :             : #include <atomic>
      23                 :             : #include <mutex>
      24                 :             : 
      25                 :             : // Constants
      26                 :             : 
      27                 :             : // Threading Globals
      28                 :             : #ifndef LMUFFB_UNIT_TEST
      29                 :             : std::atomic<bool> g_running(true);
      30                 :             : std::atomic<bool> g_ffb_active(true);
      31                 :             : 
      32                 :             : SharedMemoryObjectOut g_localData; // Local copy of shared memory
      33                 :             : 
      34                 :             : FFBEngine g_engine;
      35                 :             : std::recursive_mutex g_engine_mutex; // Protects settings access if GUI changes them
      36                 :             : #else
      37                 :             : extern std::atomic<bool> g_running;
      38                 :             : extern std::atomic<bool> g_ffb_active;
      39                 :             : extern SharedMemoryObjectOut g_localData;
      40                 :             : extern FFBEngine g_engine;
      41                 :             : extern std::recursive_mutex g_engine_mutex;
      42                 :             : #endif
      43                 :             : 
      44                 :             : // --- FFB Loop (High Priority 400Hz) ---
      45                 :           9 : void FFBThread() {
      46   [ +  -  +  - ]:           9 :     std::cout << "[FFB] Loop Started." << std::endl;
      47         [ +  - ]:           9 :     RateMonitor loopMonitor;
      48         [ +  - ]:           9 :     RateMonitor telemMonitor;
      49         [ +  - ]:           9 :     RateMonitor hwMonitor;
      50         [ +  - ]:           9 :     RateMonitor torqueMonitor;
      51         [ +  - ]:           9 :     RateMonitor genTorqueMonitor;
      52                 :           9 :     double lastET = -1.0;
      53                 :           9 :     double lastTorque = -9999.0;
      54                 :           9 :     float lastGenTorque = -9999.0f;
      55                 :             : 
      56                 :             :     // Extended monitors for Issue #133
      57                 :             :     struct ChannelMonitor {
      58                 :             :         RateMonitor monitor;
      59                 :             :         double lastValue = -1e18;
      60                 :           0 :         void Update(double newValue) {
      61         [ #  # ]:           0 :             if (newValue != lastValue) {
      62                 :           0 :                 monitor.RecordEvent();
      63                 :           0 :                 lastValue = newValue;
      64                 :             :             }
      65                 :           0 :         }
      66                 :             :     };
      67                 :             : 
      68   [ +  -  +  -  :           9 :     ChannelMonitor mAccX, mAccY, mAccZ;
                   +  - ]
      69   [ +  -  +  -  :           9 :     ChannelMonitor mVelX, mVelY, mVelZ;
                   +  - ]
      70   [ +  -  +  -  :           9 :     ChannelMonitor mRotX, mRotY, mRotZ;
                   +  - ]
      71   [ +  -  +  -  :           9 :     ChannelMonitor mRotAccX, mRotAccY, mRotAccZ;
                   +  - ]
      72   [ +  -  +  - ]:           9 :     ChannelMonitor mUnfSteer, mFilSteer;
      73         [ +  - ]:           9 :     ChannelMonitor mRPM;
      74   [ +  -  +  -  :           9 :     ChannelMonitor mLoadFL, mLoadFR, mLoadRL, mLoadRR;
             +  -  +  - ]
      75   [ +  -  +  -  :           9 :     ChannelMonitor mLatFL, mLatFR, mLatRL, mLatRR;
             +  -  +  - ]
      76   [ +  -  +  -  :           9 :     ChannelMonitor mPosX, mPosY, mPosZ;
                   +  - ]
      77         [ +  - ]:           9 :     ChannelMonitor mDtMon;
      78                 :             : 
      79                 :             :     // Precise Timing: Target 400Hz (2500 microseconds)
      80                 :           9 :     const std::chrono::microseconds target_period(2500);
      81                 :           9 :     auto next_tick = std::chrono::steady_clock::now();
      82                 :             : 
      83         [ +  + ]:        4770 :     while (g_running) {
      84         [ +  - ]:        4761 :         loopMonitor.RecordEvent();
      85   [ +  -  +  - ]:        4761 :         next_tick += target_period;
      86                 :             : 
      87                 :        4761 :         double force = 0.0;
      88                 :        4761 :         double dt = 0.0025; // Default 400Hz
      89                 :        4761 :         bool restricted = true;
      90                 :             : 
      91   [ +  -  +  -  :        4761 :         if (g_ffb_active && GameConnector::Get().IsConnected()) {
          +  -  +  -  +  
                      - ]
      92   [ +  -  +  - ]:        4761 :             bool in_realtime = GameConnector::Get().CopyTelemetry(g_localData);
      93   [ +  -  +  - ]:        4761 :             bool is_stale = GameConnector::Get().IsStale(100);
      94                 :             : 
      95                 :             :             static bool was_in_menu = true;
      96   [ +  +  +  + ]:        4761 :             if (was_in_menu && in_realtime) {
      97   [ +  -  +  - ]:           2 :                 std::cout << "[Game] User entered driving session." << std::endl;
      98   [ +  -  +  -  :           2 :                 if (Config::m_auto_start_logging && !AsyncLogger::Get().IsLogging()) {
             +  -  +  - ]
      99                 :           2 :                     SessionInfo info;
     100         [ +  - ]:           2 :                     info.app_version = LMUFFB_VERSION;
     101         [ +  - ]:           2 :                     std::lock_guard<std::recursive_mutex> lock(g_engine_mutex);
     102         [ +  - ]:           2 :                     info.vehicle_name = g_engine.m_vehicle_name;
     103         [ +  - ]:           2 :                     info.track_name = g_engine.m_track_name;
     104         [ +  - ]:           2 :                     info.driver_name = "Auto";
     105                 :           2 :                     info.gain = g_engine.m_gain;
     106                 :           2 :                     info.understeer_effect = g_engine.m_understeer_effect;
     107                 :           2 :                     info.sop_effect = g_engine.m_sop_effect;
     108                 :           2 :                     info.slope_enabled = g_engine.m_slope_detection_enabled;
     109                 :           2 :                     info.slope_sensitivity = g_engine.m_slope_sensitivity;
     110                 :           2 :                     info.slope_threshold = (float)g_engine.m_slope_min_threshold;
     111                 :           2 :                     info.slope_alpha_threshold = g_engine.m_slope_alpha_threshold;
     112                 :           2 :                     info.slope_decay_rate = g_engine.m_slope_decay_rate;
     113                 :           2 :                     info.torque_passthrough = g_engine.m_torque_passthrough;
     114   [ +  -  +  - ]:           2 :                     AsyncLogger::Get().Start(info, Config::m_log_path);
     115                 :           2 :                 }
     116   [ +  +  +  + ]:        4761 :             } else if (!was_in_menu && !in_realtime) {
     117   [ +  -  +  - ]:           1 :                 std::cout << "[Game] User exited to menu (FFB Muted)." << std::endl;
     118   [ +  -  +  -  :           1 :                 if (Config::m_auto_start_logging && AsyncLogger::Get().IsLogging()) {
             -  +  -  + ]
     119         [ #  # ]:           0 :                     AsyncLogger::Get().Stop();
     120                 :             :                 }
     121                 :             :             }
     122                 :        4761 :             was_in_menu = !in_realtime;
     123                 :             :             
     124                 :        4761 :             bool should_output = false;
     125                 :             : 
     126                 :             :             // v0.7.78 FIX: Support stationary/garage soft lock (Issue #184)
     127                 :             :             // We now process FFB even if not in realtime, provided we have a player vehicle.
     128                 :             :             // This allows Soft Lock to function in the garage or when AI is driving.
     129   [ +  -  -  + ]:        4761 :             if (!is_stale && g_localData.telemetry.playerHasVehicle) {
     130                 :           0 :                 uint8_t idx = g_localData.telemetry.playerVehicleIdx;
     131         [ #  # ]:           0 :                 if (idx < 104) {
     132                 :           0 :                     auto& scoring = g_localData.scoring.vehScoringInfo[idx];
     133                 :           0 :                     TelemInfoV01* pPlayerTelemetry = &g_localData.telemetry.telemInfo[idx];
     134                 :           0 :                     dt = pPlayerTelemetry->mDeltaTime;
     135                 :             : 
     136                 :             :                     // Track telemetry update rate
     137         [ #  # ]:           0 :                     if (pPlayerTelemetry->mElapsedTime != lastET) {
     138         [ #  # ]:           0 :                         telemMonitor.RecordEvent();
     139                 :           0 :                         lastET = pPlayerTelemetry->mElapsedTime;
     140                 :             :                     }
     141                 :             : 
     142                 :             :                     // Track torque update rates
     143         [ #  # ]:           0 :                     if (pPlayerTelemetry->mSteeringShaftTorque != lastTorque) {
     144         [ #  # ]:           0 :                         torqueMonitor.RecordEvent();
     145                 :           0 :                         lastTorque = pPlayerTelemetry->mSteeringShaftTorque;
     146                 :             :                     }
     147         [ #  # ]:           0 :                     if (g_localData.generic.FFBTorque != lastGenTorque) {
     148         [ #  # ]:           0 :                         genTorqueMonitor.RecordEvent();
     149                 :           0 :                         lastGenTorque = g_localData.generic.FFBTorque;
     150                 :             :                     }
     151                 :             : 
     152                 :             :                     // Extended monitoring (Issue #133)
     153         [ #  # ]:           0 :                     mAccX.Update(pPlayerTelemetry->mLocalAccel.x);
     154         [ #  # ]:           0 :                     mAccY.Update(pPlayerTelemetry->mLocalAccel.y);
     155         [ #  # ]:           0 :                     mAccZ.Update(pPlayerTelemetry->mLocalAccel.z);
     156         [ #  # ]:           0 :                     mVelX.Update(pPlayerTelemetry->mLocalVel.x);
     157         [ #  # ]:           0 :                     mVelY.Update(pPlayerTelemetry->mLocalVel.y);
     158         [ #  # ]:           0 :                     mVelZ.Update(pPlayerTelemetry->mLocalVel.z);
     159         [ #  # ]:           0 :                     mRotX.Update(pPlayerTelemetry->mLocalRot.x);
     160         [ #  # ]:           0 :                     mRotY.Update(pPlayerTelemetry->mLocalRot.y);
     161         [ #  # ]:           0 :                     mRotZ.Update(pPlayerTelemetry->mLocalRot.z);
     162         [ #  # ]:           0 :                     mRotAccX.Update(pPlayerTelemetry->mLocalRotAccel.x);
     163         [ #  # ]:           0 :                     mRotAccY.Update(pPlayerTelemetry->mLocalRotAccel.y);
     164         [ #  # ]:           0 :                     mRotAccZ.Update(pPlayerTelemetry->mLocalRotAccel.z);
     165         [ #  # ]:           0 :                     mUnfSteer.Update(pPlayerTelemetry->mUnfilteredSteering);
     166         [ #  # ]:           0 :                     mFilSteer.Update(pPlayerTelemetry->mFilteredSteering);
     167         [ #  # ]:           0 :                     mRPM.Update(pPlayerTelemetry->mEngineRPM);
     168         [ #  # ]:           0 :                     mLoadFL.Update(pPlayerTelemetry->mWheel[0].mTireLoad);
     169         [ #  # ]:           0 :                     mLoadFR.Update(pPlayerTelemetry->mWheel[1].mTireLoad);
     170         [ #  # ]:           0 :                     mLoadRL.Update(pPlayerTelemetry->mWheel[2].mTireLoad);
     171         [ #  # ]:           0 :                     mLoadRR.Update(pPlayerTelemetry->mWheel[3].mTireLoad);
     172         [ #  # ]:           0 :                     mLatFL.Update(pPlayerTelemetry->mWheel[0].mLateralForce);
     173         [ #  # ]:           0 :                     mLatFR.Update(pPlayerTelemetry->mWheel[1].mLateralForce);
     174         [ #  # ]:           0 :                     mLatRL.Update(pPlayerTelemetry->mWheel[2].mLateralForce);
     175         [ #  # ]:           0 :                     mLatRR.Update(pPlayerTelemetry->mWheel[3].mLateralForce);
     176         [ #  # ]:           0 :                     mPosX.Update(pPlayerTelemetry->mPos.x);
     177         [ #  # ]:           0 :                     mPosY.Update(pPlayerTelemetry->mPos.y);
     178         [ #  # ]:           0 :                     mPosZ.Update(pPlayerTelemetry->mPos.z);
     179         [ #  # ]:           0 :                     mDtMon.Update(pPlayerTelemetry->mDeltaTime);
     180                 :             : 
     181         [ #  # ]:           0 :                     std::lock_guard<std::recursive_mutex> lock(g_engine_mutex);
     182                 :             :                     // Determine if full FFB is allowed.
     183                 :             :                     // full_allowed requires: player control, not disqualified, and in realtime.
     184   [ #  #  #  #  :           0 :                     bool full_allowed = g_engine.IsFFBAllowed(scoring, g_localData.scoring.scoringInfo.mGamePhase) && in_realtime;
                   #  # ]
     185                 :             : 
     186                 :             :                     // v0.7.108: Explicitly zero force if not in realtime (Issue #174).
     187                 :             :                     // We still call calculate_force to keep engine state updated, but override the result.
     188                 :             :                     // This ensures the safety slew limiter can smoothly relax the wheel.
     189         [ #  # ]:           0 :                     force = g_engine.calculate_force(pPlayerTelemetry, scoring.mVehicleClass, scoring.mVehicleName, g_localData.generic.FFBTorque, full_allowed);
     190         [ #  # ]:           0 :                     if (!in_realtime) force = 0.0;
     191                 :           0 :                     should_output = true;
     192                 :             : 
     193                 :             :                     // If not full_allowed, use tighter slew rate limiting
     194   [ #  #  #  # ]:           0 :                     restricted = !full_allowed || (scoring.mFinishStatus != 0);
     195                 :           0 :                 }
     196                 :             :             }
     197                 :             :             
     198         [ +  - ]:        4761 :             if (!should_output) force = 0.0;
     199                 :             : 
     200                 :             :             // Warning for low sample rate (Issue #133)
     201   [ +  +  +  - ]:        4761 :             static auto lastWarningTime = std::chrono::steady_clock::now();
     202                 :             : 
     203                 :        4761 :             HealthStatus health;
     204                 :             :             {
     205         [ +  - ]:        4761 :                 std::lock_guard<std::recursive_mutex> lock(g_engine_mutex);
     206         [ -  + ]:        4761 :                 double t_rate = (g_engine.m_torque_source == 1) ? genTorqueMonitor.GetRate() : torqueMonitor.GetRate();
     207                 :        4761 :                 health = HealthMonitor::Check(loopMonitor.GetRate(), telemMonitor.GetRate(), t_rate, g_engine.m_torque_source);
     208                 :        4761 :             }
     209                 :             : 
     210   [ +  +  -  + ]:        4761 :             if (in_realtime && !health.is_healthy) {
     211                 :           0 :                  auto now = std::chrono::steady_clock::now();
     212   [ #  #  #  #  :           0 :                  if (std::chrono::duration_cast<std::chrono::seconds>(now - lastWarningTime).count() >= 5) {
                   #  # ]
     213         [ #  # ]:           0 :                      std::string reason = "";
     214   [ #  #  #  #  :           0 :                      if (health.loop_low) reason += "Loop=" + std::to_string((int)health.loop_rate) + "Hz ";
             #  #  #  # ]
     215   [ #  #  #  #  :           0 :                      if (health.telem_low) reason += "Telemetry=" + std::to_string((int)health.telem_rate) + "Hz ";
             #  #  #  # ]
     216   [ #  #  #  #  :           0 :                      if (health.torque_low) reason += "Torque=" + std::to_string((int)health.torque_rate) + "Hz (Target " + std::to_string((int)health.expected_torque_rate) + "Hz) ";
          #  #  #  #  #  
                #  #  # ]
     217                 :             : 
     218   [ #  #  #  #  :           0 :                      std::cout << "[WARNING] Low Sample Rate detected: " << reason << std::endl;
                   #  # ]
     219   [ #  #  #  # ]:           0 :                      Logger::Get().Log("Low Sample Rate detected: %s", reason.c_str());
     220                 :           0 :                      lastWarningTime = now;
     221                 :           0 :                  }
     222                 :             :             }
     223                 :             :         }
     224                 :             : 
     225                 :             :         // Safety Layer (v0.7.49): Slew Rate Limiting and NaN protection
     226                 :             :         // v0.7.48: Always update hardware even if disconnected/inactive to ensure zeroing
     227                 :             :         {
     228         [ +  - ]:        4761 :             std::lock_guard<std::recursive_mutex> lock(g_engine_mutex);
     229         [ -  + ]:        4761 :             if (dt < 0.0001) dt = 0.0025;
     230                 :             : 
     231                 :             :             // Push rates to engine for GUI/Snapshot
     232                 :        4761 :             g_engine.m_ffb_rate = loopMonitor.GetRate();
     233                 :        4761 :             g_engine.m_telemetry_rate = telemMonitor.GetRate();
     234                 :        4761 :             g_engine.m_hw_rate = hwMonitor.GetRate();
     235                 :        4761 :             g_engine.m_torque_rate = torqueMonitor.GetRate();
     236                 :        4761 :             g_engine.m_gen_torque_rate = genTorqueMonitor.GetRate();
     237                 :             : 
     238         [ +  - ]:        4761 :             force = g_engine.ApplySafetySlew(force, dt, restricted);  // TODO: review for correctedness and bugs
     239                 :        4761 :         }
     240                 :             : 
     241   [ +  -  +  -  :        4761 :         if (DirectInputFFB::Get().UpdateForce(force)) {
                   -  + ]
     242         [ #  # ]:           0 :             hwMonitor.RecordEvent();
     243                 :             :         }
     244                 :             : 
     245                 :             :         // Extended Logging (Issue #133)
     246   [ +  +  +  - ]:        4761 :         static auto lastExtLogTime = std::chrono::steady_clock::now();
     247                 :        4761 :         auto now = std::chrono::steady_clock::now();
     248   [ +  -  +  -  :        4761 :         if (std::chrono::duration_cast<std::chrono::seconds>(now - lastExtLogTime).count() >= 5) {
                   +  + ]
     249                 :           2 :             lastExtLogTime = now;
     250   [ +  -  +  -  :           2 :             if (GameConnector::Get().IsConnected() && g_localData.telemetry.playerHasVehicle) {
          +  -  -  +  -  
                      + ]
     251   [ #  #  #  # ]:           0 :                 Logger::Get().Log("--- Telemetry Sample Rates (Hz) ---");
     252   [ #  #  #  # ]:           0 :                 Logger::Get().Log("Loop: %.1f, ET: %.1f, HW: %.1f", loopMonitor.GetRate(), telemMonitor.GetRate(), hwMonitor.GetRate());
     253   [ #  #  #  # ]:           0 :                 Logger::Get().Log("Torque: Shaft=%.1f, Generic=%.1f", torqueMonitor.GetRate(), genTorqueMonitor.GetRate());
     254   [ #  #  #  # ]:           0 :                 Logger::Get().Log("Accel: X=%.1f, Y=%.1f, Z=%.1f", mAccX.monitor.GetRate(), mAccY.monitor.GetRate(), mAccZ.monitor.GetRate());
     255   [ #  #  #  # ]:           0 :                 Logger::Get().Log("Vel: X=%.1f, Y=%.1f, Z=%.1f", mVelX.monitor.GetRate(), mVelY.monitor.GetRate(), mVelZ.monitor.GetRate());
     256   [ #  #  #  # ]:           0 :                 Logger::Get().Log("Rot: X=%.1f, Y=%.1f, Z=%.1f", mRotX.monitor.GetRate(), mRotY.monitor.GetRate(), mRotZ.monitor.GetRate());
     257   [ #  #  #  # ]:           0 :                 Logger::Get().Log("RotAcc: X=%.1f, Y=%.1f, Z=%.1f", mRotAccX.monitor.GetRate(), mRotAccY.monitor.GetRate(), mRotAccZ.monitor.GetRate());
     258   [ #  #  #  # ]:           0 :                 Logger::Get().Log("Steering: Unf=%.1f, Fil=%.1f, RPM=%.1f", mUnfSteer.monitor.GetRate(), mFilSteer.monitor.GetRate(), mRPM.monitor.GetRate());
     259   [ #  #  #  # ]:           0 :                 Logger::Get().Log("Load: FL=%.1f, FR=%.1f, RL=%.1f, RR=%.1f", mLoadFL.monitor.GetRate(), mLoadFR.monitor.GetRate(), mLoadRL.monitor.GetRate(), mLoadRR.monitor.GetRate());
     260   [ #  #  #  # ]:           0 :                 Logger::Get().Log("LatForce: FL=%.1f, FR=%.1f, RL=%.1f, RR=%.1f", mLatFL.monitor.GetRate(), mLatFR.monitor.GetRate(), mLatRL.monitor.GetRate(), mLatRR.monitor.GetRate());
     261   [ #  #  #  # ]:           0 :                 Logger::Get().Log("Pos: X=%.1f, Y=%.1f, Z=%.1f, DeltaTime=%.1f", mPosX.monitor.GetRate(), mPosY.monitor.GetRate(), mPosZ.monitor.GetRate(), mDtMon.monitor.GetRate());
     262   [ #  #  #  # ]:           0 :                 Logger::Get().Log("-----------------------------------");
     263                 :             :             }
     264                 :             :         }
     265                 :             : 
     266                 :             :         // Precise Timing: Sleep until next tick
     267         [ +  - ]:        4761 :         std::this_thread::sleep_until(next_tick);
     268                 :             :     }
     269                 :             : 
     270   [ +  -  +  - ]:           9 :     std::cout << "[FFB] Loop Stopped." << std::endl;
     271                 :           9 : }
     272                 :             : 
     273                 :             : #ifndef _WIN32
     274                 :           2 : void handle_sigterm(int sig) {
     275                 :           2 :     g_running = false;
     276                 :           2 : }
     277                 :             : #endif
     278                 :             : 
     279                 :             : #ifdef LMUFFB_UNIT_TEST
     280                 :           4 : int lmuffb_app_main(int argc, char* argv[]) noexcept {
     281                 :             : #else
     282                 :             : int main(int argc, char* argv[]) noexcept {
     283                 :             : #endif
     284                 :             :     try {
     285                 :             : #ifdef _WIN32
     286                 :             :         timeBeginPeriod(1);
     287                 :             : #else
     288                 :           4 :         signal(SIGTERM, handle_sigterm);
     289                 :           4 :         signal(SIGINT, handle_sigterm);
     290                 :             : #endif
     291                 :             : 
     292                 :           4 :     bool headless = false;
     293         [ +  + ]:           8 :     for (int i = 1; i < argc; ++i) {
     294   [ +  -  +  -  :           8 :         if (std::string(argv[i]) == "--headless") headless = true;
                   +  + ]
     295                 :             :     }
     296                 :             : 
     297   [ +  -  +  - ]:           4 :     std::cout << "Starting lmuFFB (C++ Port)..." << std::endl;
     298                 :             :     // Initialize persistent debug logging for crash analysis
     299   [ +  -  +  -  :           8 :     Logger::Get().Init("lmuffb_debug.log");
                   +  - ]
     300   [ +  -  +  - ]:           4 :     Logger::Get().Log("Application Started. Version: %s", LMUFFB_VERSION);
     301   [ +  +  +  -  :           4 :     if (headless) Logger::Get().Log("Mode: HEADLESS");
                   +  - ]
     302   [ +  -  +  - ]:           1 :     else Logger::Get().Log("Mode: GUI");
     303                 :             : 
     304         [ +  - ]:           4 :     Preset::ApplyDefaultsToEngine(g_engine);
     305   [ +  -  +  - ]:           4 :     Config::Load(g_engine);
     306                 :             : 
     307         [ +  + ]:           4 :     if (!headless) {
     308   [ +  -  -  + ]:           1 :         if (!GuiLayer::Init()) {
     309   [ #  #  #  # ]:           0 :             std::cerr << "Failed to initialize GUI." << std::endl;
     310                 :             :         }
     311   [ +  -  +  -  :           1 :         DirectInputFFB::Get().Initialize(reinterpret_cast<HWND>(GuiLayer::GetWindowHandle()));
                   +  - ]
     312                 :             :     } else {
     313   [ +  -  +  - ]:           3 :         std::cout << "Running in HEADLESS mode." << std::endl;
     314   [ +  -  +  - ]:           3 :         DirectInputFFB::Get().Initialize(NULL);
     315                 :             :     }
     316                 :             : 
     317   [ +  -  +  -  :           4 :     if (GameConnector::Get().CheckLegacyConflict()) {
                   -  + ]
     318   [ #  #  #  # ]:           0 :         std::cout << "[Info] Legacy rF2 plugin detected (not a problem for LMU 1.2+)" << std::endl;
     319                 :             :     }
     320                 :             : 
     321   [ +  -  +  -  :           4 :     if (!GameConnector::Get().TryConnect()) {
                   -  + ]
     322   [ #  #  #  # ]:           0 :         std::cout << "Game not running or Shared Memory not ready. Waiting..." << std::endl;
     323                 :             :     }
     324                 :             : 
     325         [ +  - ]:           4 :     std::thread ffb_thread(FFBThread);
     326   [ +  -  +  - ]:           4 :     std::cout << "[GUI] Main Loop Started." << std::endl;
     327                 :             : 
     328         [ +  + ]:          30 :     while (g_running) {
     329         [ +  - ]:          26 :         GuiLayer::Render(g_engine);
     330                 :             : 
     331                 :             :         // Process background save requests from the FFB thread (v0.7.70)
     332         [ +  + ]:          26 :         if (Config::m_needs_save.exchange(false)) {
     333   [ +  -  +  - ]:           2 :             Config::Save(g_engine);
     334                 :             :         }
     335                 :             : 
     336                 :             :         // Maintain a consistent 60Hz message loop even when backgrounded
     337                 :             :         // to ensure DirectInput performance and reliability.
     338         [ +  - ]:          26 :         std::this_thread::sleep_for(std::chrono::milliseconds(16));
     339                 :             :     }
     340                 :             :     
     341   [ +  -  +  - ]:           4 :     Config::Save(g_engine);
     342         [ +  + ]:           4 :     if (!headless) {
     343   [ +  -  +  - ]:           1 :         Logger::Get().Log("Shutting down GUI...");
     344         [ +  - ]:           1 :         GuiLayer::Shutdown(g_engine);
     345                 :             :     }
     346         [ +  - ]:           4 :     if (ffb_thread.joinable()) {
     347   [ +  -  +  - ]:           4 :         Logger::Get().Log("Stopping FFB Thread...");
     348                 :           4 :         g_running = false; // Ensure loop breaks
     349         [ +  - ]:           4 :         ffb_thread.join();
     350   [ +  -  +  - ]:           4 :         Logger::Get().Log("FFB Thread Stopped.");
     351                 :             :     }
     352   [ +  -  +  - ]:           4 :     DirectInputFFB::Get().Shutdown();
     353   [ +  -  +  - ]:           4 :     Logger::Get().Log("Main Loop Ended. Clean Exit.");
     354                 :             :     
     355                 :           4 :     return 0;
     356         [ -  - ]:           4 :     } catch (const std::exception& e) {
     357                 :           0 :         fprintf(stderr, "Fatal exception: %s\n", e.what());
     358                 :             :         // Attempt to log if possible, but don't risk more throws
     359   [ -  -  -  - ]:           0 :         try { Logger::Get().Log("Fatal exception: %s", e.what()); } catch(...) { (void)0; }
     360                 :           0 :         return 1;
     361                 :           0 :     } catch (...) {
     362                 :           0 :         fprintf(stderr, "Fatal unknown exception.\n");
     363   [ -  -  -  - ]:           0 :         try { Logger::Get().Log("Fatal unknown exception."); } catch(...) { (void)0; }
     364                 :           0 :         return 1;
     365                 :           0 :     }
     366                 :             : }
        

Generated by: LCOV version 2.0-1