main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. #include <QCoreApplication>
  2. #include <QDateTime>
  3. #include <QDebug>
  4. #include <QDir>
  5. #include <QFile>
  6. #include <QGuiApplication>
  7. #include <QOffscreenSurface>
  8. #include <QOpenGLContext>
  9. #include <QOpenGLFunctions>
  10. #include <QQmlApplicationEngine>
  11. #include <QQmlContext>
  12. #include <QQuickWindow>
  13. #include <QSGRendererInterface>
  14. #include <QSurfaceFormat>
  15. #include <QTextStream>
  16. #include <QUrl>
  17. #include <cstdio>
  18. #include <memory>
  19. #include <qglobal.h>
  20. #include <qguiapplication.h>
  21. #include <qnamespace.h>
  22. #include <qobject.h>
  23. #include <qqml.h>
  24. #include <qqmlapplicationengine.h>
  25. #include <qsgrendererinterface.h>
  26. #include <qstringliteral.h>
  27. #include <qstringview.h>
  28. #include <qsurfaceformat.h>
  29. #include <qurl.h>
  30. #ifdef Q_OS_WIN
  31. #include <QProcess>
  32. #include <gl/gl.h>
  33. #include <windows.h>
  34. #pragma comment(lib, "opengl32.lib")
  35. #endif
  36. #include "app/core/game_engine.h"
  37. #include "app/core/language_manager.h"
  38. #include "app/models/graphics_settings_proxy.h"
  39. #include "app/models/minimap_image_provider.h"
  40. #include "ui/gl_view.h"
  41. #include "ui/theme.h"
  42. // Constants replacing magic numbers
  43. constexpr int k_depth_buffer_bits = 24;
  44. constexpr int k_stencil_buffer_bits = 8;
  45. #ifdef Q_OS_WIN
  46. // Test OpenGL using native Win32 API (before any Qt initialization)
  47. // Returns true if OpenGL is available, false otherwise
  48. static bool testNativeOpenGL() {
  49. WNDCLASSA wc = {};
  50. wc.lpfnWndProc = DefWindowProcA;
  51. wc.hInstance = GetModuleHandle(nullptr);
  52. wc.lpszClassName = "OpenGLTest";
  53. if (!RegisterClassA(&wc)) {
  54. return false;
  55. }
  56. HWND hwnd = CreateWindowExA(0, "OpenGLTest", "", WS_OVERLAPPEDWINDOW, 0, 0, 1,
  57. 1, nullptr, nullptr, wc.hInstance, nullptr);
  58. if (!hwnd) {
  59. UnregisterClassA("OpenGLTest", wc.hInstance);
  60. return false;
  61. }
  62. HDC hdc = GetDC(hwnd);
  63. if (!hdc) {
  64. DestroyWindow(hwnd);
  65. UnregisterClassA("OpenGLTest", wc.hInstance);
  66. return false;
  67. }
  68. PIXELFORMATDESCRIPTOR pfd = {};
  69. pfd.nSize = sizeof(pfd);
  70. pfd.nVersion = 1;
  71. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  72. pfd.iPixelType = PFD_TYPE_RGBA;
  73. pfd.cColorBits = 24;
  74. pfd.cDepthBits = 24;
  75. pfd.cStencilBits = 8;
  76. pfd.iLayerType = PFD_MAIN_PLANE;
  77. int pixelFormat = ChoosePixelFormat(hdc, &pfd);
  78. bool success = false;
  79. if (pixelFormat != 0 && SetPixelFormat(hdc, pixelFormat, &pfd)) {
  80. HGLRC hglrc = wglCreateContext(hdc);
  81. if (hglrc) {
  82. if (wglMakeCurrent(hdc, hglrc)) {
  83. // Successfully created OpenGL context
  84. const char *vendor = (const char *)glGetString(GL_VENDOR);
  85. const char *renderer = (const char *)glGetString(GL_RENDERER);
  86. const char *version = (const char *)glGetString(GL_VERSION);
  87. if (vendor && renderer && version) {
  88. fprintf(stderr,
  89. "[OpenGL Test] Native context created successfully\n");
  90. fprintf(stderr, "[OpenGL Test] Vendor: %s\n", vendor);
  91. fprintf(stderr, "[OpenGL Test] Renderer: %s\n", renderer);
  92. fprintf(stderr, "[OpenGL Test] Version: %s\n", version);
  93. success = true;
  94. }
  95. wglMakeCurrent(nullptr, nullptr);
  96. }
  97. wglDeleteContext(hglrc);
  98. }
  99. }
  100. ReleaseDC(hwnd, hdc);
  101. DestroyWindow(hwnd);
  102. UnregisterClassA("OpenGLTest", wc.hInstance);
  103. return success;
  104. }
  105. // Windows crash handler to detect OpenGL failures and suggest fallback
  106. static bool g_opengl_crashed = false;
  107. static LONG WINAPI crashHandler(EXCEPTION_POINTERS *exceptionInfo) {
  108. if (exceptionInfo->ExceptionRecord->ExceptionCode ==
  109. EXCEPTION_ACCESS_VIOLATION) {
  110. // Log crash
  111. FILE *crash_log = fopen("opengl_crash.txt", "w");
  112. if (crash_log) {
  113. fprintf(crash_log,
  114. "OpenGL/Qt rendering crash detected (Access Violation)\n");
  115. fprintf(crash_log, "Try running with: run_debug_softwaregl.cmd\n");
  116. fprintf(crash_log,
  117. "Or set environment variable: QT_QUICK_BACKEND=software\n");
  118. fclose(crash_log);
  119. }
  120. qCritical() << "=== CRASH DETECTED ===";
  121. qCritical() << "OpenGL rendering failed. This usually means:";
  122. qCritical() << "1. Graphics drivers are outdated";
  123. qCritical() << "2. Running in a VM with incomplete OpenGL support";
  124. qCritical() << "3. GPU doesn't support required OpenGL version";
  125. qCritical() << "";
  126. qCritical() << "To fix: Run run_debug_softwaregl.cmd instead";
  127. qCritical() << "Or set: set QT_QUICK_BACKEND=software";
  128. g_opengl_crashed = true;
  129. }
  130. return EXCEPTION_CONTINUE_SEARCH;
  131. }
  132. #endif
  133. auto main(int argc, char *argv[]) -> int {
  134. #ifdef Q_OS_WIN
  135. // Install crash handler to detect OpenGL failures
  136. SetUnhandledExceptionFilter(crashHandler);
  137. // Test OpenGL BEFORE any Qt initialization (using native Win32 API)
  138. fprintf(stderr, "[Pre-Init] Testing native OpenGL availability...\n");
  139. bool opengl_available = testNativeOpenGL();
  140. if (!opengl_available) {
  141. fprintf(stderr, "[Pre-Init] WARNING: OpenGL test failed!\n");
  142. fprintf(stderr, "[Pre-Init] Forcing software rendering mode\n");
  143. _putenv("QT_QUICK_BACKEND=software");
  144. _putenv("QT_OPENGL=software");
  145. } else {
  146. fprintf(stderr, "[Pre-Init] OpenGL test passed\n");
  147. }
  148. // Check if we should use software rendering
  149. bool use_software = qEnvironmentVariableIsSet("QT_QUICK_BACKEND") &&
  150. qEnvironmentVariable("QT_QUICK_BACKEND") == "software";
  151. if (use_software) {
  152. qInfo() << "=== SOFTWARE RENDERING MODE ===";
  153. qInfo() << "Using Qt Quick Software renderer (CPU-based)";
  154. qInfo() << "Performance will be limited but should work on all systems";
  155. }
  156. #endif
  157. // Setup message handler for debugging
  158. qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &context,
  159. const QString &msg) {
  160. QByteArray const local_msg = msg.toLocal8Bit();
  161. const char *file = (context.file != nullptr) ? context.file : "";
  162. const char *function =
  163. (context.function != nullptr) ? context.function : "";
  164. FILE *out = stderr;
  165. switch (type) {
  166. case QtDebugMsg:
  167. fprintf(out, "[DEBUG] %s (%s:%u, %s)\n", local_msg.constData(), file,
  168. context.line, function);
  169. break;
  170. case QtInfoMsg:
  171. fprintf(out, "[INFO] %s\n", local_msg.constData());
  172. break;
  173. case QtWarningMsg:
  174. fprintf(out, "[WARNING] %s (%s:%u, %s)\n", local_msg.constData(), file,
  175. context.line, function);
  176. // Check for critical OpenGL warnings
  177. if (msg.contains("OpenGL", Qt::CaseInsensitive) ||
  178. msg.contains("scene graph", Qt::CaseInsensitive) ||
  179. msg.contains("RHI", Qt::CaseInsensitive)) {
  180. fprintf(out, "[HINT] If you see crashes, try software rendering: set "
  181. "QT_QUICK_BACKEND=software\n");
  182. }
  183. break;
  184. case QtCriticalMsg:
  185. fprintf(out, "[CRITICAL] %s (%s:%u, %s)\n", local_msg.constData(), file,
  186. context.line, function);
  187. fprintf(
  188. out,
  189. "[CRITICAL] Try running with software rendering if this persists\n");
  190. break;
  191. case QtFatalMsg:
  192. fprintf(out, "[FATAL] %s (%s:%u, %s)\n", local_msg.constData(), file,
  193. context.line, function);
  194. fprintf(out, "[FATAL] === RECOVERY SUGGESTION ===\n");
  195. fprintf(out, "[FATAL] Run: run_debug_softwaregl.cmd\n");
  196. fprintf(out, "[FATAL] Or set: QT_QUICK_BACKEND=software\n");
  197. abort();
  198. }
  199. fflush(out);
  200. });
  201. qInfo() << "=== Standard of Iron - Starting ===";
  202. qInfo() << "Qt version:" << QT_VERSION_STR;
  203. // Linux-specific: prefer X11 over Wayland for better OpenGL compatibility
  204. #ifndef Q_OS_WIN
  205. if (qEnvironmentVariableIsSet("WAYLAND_DISPLAY") &&
  206. qEnvironmentVariableIsSet("DISPLAY")) {
  207. qputenv("QT_QPA_PLATFORM", "xcb");
  208. qInfo() << "Linux: Using X11 (xcb) platform";
  209. }
  210. #endif
  211. qInfo() << "Setting OpenGL environment...";
  212. qputenv("QT_OPENGL", "desktop");
  213. qputenv("QSG_RHI_BACKEND", "opengl");
  214. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  215. qInfo() << "Setting graphics API to OpenGLRhi...";
  216. QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGLRhi);
  217. #endif
  218. qInfo() << "Configuring OpenGL surface format...";
  219. QSurfaceFormat fmt;
  220. fmt.setVersion(3, 3);
  221. fmt.setProfile(QSurfaceFormat::CoreProfile);
  222. fmt.setDepthBufferSize(k_depth_buffer_bits);
  223. fmt.setStencilBufferSize(k_stencil_buffer_bits);
  224. fmt.setSamples(0);
  225. #ifdef Q_OS_WIN
  226. // Windows: Request compatibility profile for better driver support
  227. // Some Windows drivers have issues with Core profile on older hardware
  228. fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
  229. qInfo() << "Windows detected: Using OpenGL Compatibility Profile";
  230. #endif
  231. QSurfaceFormat::setDefaultFormat(fmt);
  232. qInfo() << "Surface format configured: OpenGL" << fmt.majorVersion() << "."
  233. << fmt.minorVersion();
  234. qInfo() << "Creating QGuiApplication...";
  235. QGuiApplication app(argc, argv);
  236. qInfo() << "QGuiApplication created successfully";
  237. // Use unique_ptr with custom deleter for Qt objects
  238. // This ensures proper cleanup order and prevents segfaults
  239. std::unique_ptr<LanguageManager> language_manager;
  240. std::unique_ptr<GameEngine> game_engine;
  241. std::unique_ptr<App::Models::GraphicsSettingsProxy> graphics_settings;
  242. std::unique_ptr<QQmlApplicationEngine> engine;
  243. qInfo() << "Creating LanguageManager...";
  244. language_manager = std::make_unique<LanguageManager>(&app);
  245. qInfo() << "LanguageManager created";
  246. qInfo() << "Creating GameEngine...";
  247. game_engine = std::make_unique<GameEngine>(&app);
  248. qInfo() << "GameEngine created";
  249. qInfo() << "Creating GraphicsSettingsProxy...";
  250. graphics_settings =
  251. std::make_unique<App::Models::GraphicsSettingsProxy>(&app);
  252. qInfo() << "GraphicsSettingsProxy created";
  253. qInfo() << "Setting up QML engine...";
  254. engine = std::make_unique<QQmlApplicationEngine>();
  255. // Register minimap image provider
  256. qInfo() << "Registering minimap image provider...";
  257. auto *minimap_provider = new MinimapImageProvider();
  258. engine->addImageProvider("minimap", minimap_provider);
  259. qInfo() << "Adding context properties...";
  260. engine->rootContext()->setContextProperty("languageManager",
  261. language_manager.get());
  262. engine->rootContext()->setContextProperty("game", game_engine.get());
  263. engine->rootContext()->setContextProperty("graphicsSettings",
  264. graphics_settings.get());
  265. // Connect minimap image updates to the provider with DirectConnection
  266. // This ensures the image is set in the provider BEFORE QML reacts to the
  267. // signal
  268. QObject::connect(
  269. game_engine.get(), &GameEngine::minimap_image_changed, &app,
  270. [minimap_provider, game_engine_ptr = game_engine.get()]() {
  271. minimap_provider->set_minimap_image(game_engine_ptr->minimap_image());
  272. },
  273. Qt::DirectConnection);
  274. // Set initial minimap image if available
  275. if (!game_engine->minimap_image().isNull()) {
  276. qInfo() << "Setting initial minimap image";
  277. minimap_provider->set_minimap_image(game_engine->minimap_image());
  278. }
  279. qInfo() << "Adding import path...";
  280. engine->addImportPath("qrc:/StandardOfIron/ui/qml");
  281. engine->addImportPath("qrc:/");
  282. qInfo() << "Registering QML types...";
  283. qmlRegisterType<GLView>("StandardOfIron", 1, 0, "GLView");
  284. // Register Theme singleton
  285. qmlRegisterSingletonType<Theme>("StandardOfIron", 1, 0, "Theme",
  286. &Theme::create);
  287. // Register StyleGuide singleton from QML file
  288. qmlRegisterSingletonType(QUrl("qrc:/StandardOfIron/ui/qml/StyleGuide.qml"),
  289. "StandardOfIron", 1, 0, "StyleGuide");
  290. qInfo() << "Loading Main.qml...";
  291. qInfo() << "Loading Main.qml...";
  292. engine->load(QUrl(QStringLiteral("qrc:/StandardOfIron/ui/qml/Main.qml")));
  293. qInfo() << "Checking if QML loaded...";
  294. if (engine->rootObjects().isEmpty()) {
  295. qWarning() << "Failed to load QML file";
  296. return -1;
  297. }
  298. qInfo() << "QML loaded successfully, root objects count:"
  299. << engine->rootObjects().size();
  300. // Connect language changed signal to retranslate QML
  301. qInfo() << "Connecting language change handler...";
  302. QObject::connect(language_manager.get(), &LanguageManager::languageChanged,
  303. engine.get(), &QQmlApplicationEngine::retranslate);
  304. qInfo() << "Language change handler connected";
  305. qInfo() << "Finding QQuickWindow...";
  306. auto *root_obj = engine->rootObjects().first();
  307. auto *window = qobject_cast<QQuickWindow *>(root_obj);
  308. if (window == nullptr) {
  309. qInfo() << "Root object is not a window, searching children...";
  310. window = root_obj->findChild<QQuickWindow *>();
  311. }
  312. if (window == nullptr) {
  313. qWarning() << "No QQuickWindow found for OpenGL initialization.";
  314. return -2;
  315. }
  316. qInfo() << "QQuickWindow found";
  317. qInfo() << "Setting window in GameEngine...";
  318. game_engine->setWindow(window);
  319. qInfo() << "Window set successfully";
  320. qInfo() << "Connecting scene graph signals...";
  321. qInfo() << "Connecting scene graph signals...";
  322. QObject::connect(
  323. window, &QQuickWindow::sceneGraphInitialized, window, [window]() {
  324. qInfo() << "Scene graph initialized!";
  325. if (auto *renderer_interface = window->rendererInterface()) {
  326. const auto api = renderer_interface->graphicsApi();
  327. QString name;
  328. switch (api) {
  329. case QSGRendererInterface::OpenGLRhi:
  330. name = "OpenGLRhi";
  331. break;
  332. case QSGRendererInterface::VulkanRhi:
  333. name = "VulkanRhi";
  334. break;
  335. case QSGRendererInterface::Direct3D11Rhi:
  336. name = "D3D11Rhi";
  337. break;
  338. case QSGRendererInterface::MetalRhi:
  339. name = "MetalRhi";
  340. break;
  341. case QSGRendererInterface::Software:
  342. name = "Software";
  343. break;
  344. default:
  345. name = "Unknown";
  346. break;
  347. }
  348. qInfo() << "QSG graphicsApi:" << name;
  349. }
  350. });
  351. QObject::connect(window, &QQuickWindow::sceneGraphError, &app,
  352. [&](QQuickWindow::SceneGraphError, const QString &msg) {
  353. qCritical()
  354. << "Failed to initialize OpenGL scene graph:" << msg;
  355. QGuiApplication::exit(3);
  356. });
  357. qInfo() << "Starting event loop...";
  358. int const result = QGuiApplication::exec();
  359. // Explicitly destroy in correct order to prevent segfault
  360. qInfo() << "Shutting down...";
  361. // Destroy QML engine first (destroys OpenGL context)
  362. engine.reset();
  363. qInfo() << "QML engine destroyed";
  364. // Then destroy game engine
  365. // OpenGL cleanup in destructors will be skipped if no valid context
  366. game_engine.reset();
  367. qInfo() << "GameEngine destroyed";
  368. // Finally destroy language manager
  369. language_manager.reset();
  370. qInfo() << "LanguageManager destroyed";
  371. #ifdef Q_OS_WIN
  372. // Check if we crashed during OpenGL initialization
  373. if (g_opengl_crashed) {
  374. qCritical() << "";
  375. qCritical() << "========================================";
  376. qCritical() << "OPENGL CRASH RECOVERY";
  377. qCritical() << "========================================";
  378. qCritical() << "";
  379. qCritical() << "The application crashed during OpenGL initialization.";
  380. qCritical()
  381. << "This is a known issue with Qt + some Windows graphics drivers.";
  382. qCritical() << "";
  383. qCritical() << "SOLUTION: Set environment variable before running:";
  384. qCritical() << " set QT_QUICK_BACKEND=software";
  385. qCritical() << "";
  386. qCritical() << "Or use the provided launcher:";
  387. qCritical() << " run_debug_softwaregl.cmd";
  388. qCritical() << "";
  389. return -1;
  390. }
  391. #endif
  392. return result;
  393. }