main.cpp 13 KB

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