From ee64a0656f11f1ce56b5270d121369dc87d948e7 Mon Sep 17 00:00:00 2001
From: n0F4x <ggabor2002@gmail.com>
Date: Sun, 7 Jul 2024 12:08:58 +0200
Subject: [PATCH] Refactor GLFW initialization

---
 src/Window.cpp | 38 +++++++++++++++++++++++++-------------
 1 file changed, 25 insertions(+), 13 deletions(-)

diff --git a/src/Window.cpp b/src/Window.cpp
index bab07e4..b59f868 100644
--- a/src/Window.cpp
+++ b/src/Window.cpp
@@ -3,21 +3,35 @@
 #include <format>
 #include <stdexcept>
 
-[[nodiscard]]
-static auto
-    create_window(const uint16_t width, const uint16_t height, const std::string& title)
-        -> GLFWwindow*
+static auto init_glfw() -> void
 {
-    if (const auto error_code{ glfwInit() }; error_code != GLFW_TRUE) {
-        throw std::runtime_error{
-            std::format("glfwInit failed with error code {}", error_code)
-        };
+    if (const int success{ glfwInit() }; success != GLFW_TRUE) {
+        const char* description{};
+        const int   error_code{ glfwGetError(&description) };
+
+        if (description == nullptr) {
+            throw std::runtime_error{
+                std::format("glfwInit failed with error code {}", error_code)
+            };
+        }
+        throw std::runtime_error{ std::format(
+            "glfwInit failed with error code {} - '{}'", error_code, description
+        ) };
     }
-    if (const auto result{ std::atexit(glfwTerminate) }; result != 0) {
+
+    if (const int result{ std::atexit(glfwTerminate) }; result != 0) {
         throw std::runtime_error{
-            std::format("std::atexit(glfwTerminate) failed with error code {}", result)
+            std::format("std::atexit failed with error code {}", result)
         };
     }
+}
+
+[[nodiscard]]
+static auto
+    create_window(const uint16_t width, const uint16_t height, const std::string& title)
+        -> GLFWwindow*
+{
+    init_glfw();
 
     glfwDefaultWindowHints();
     glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
@@ -34,9 +48,7 @@ static auto
 auto Window::vulkan_instance_extensions() -> std::span<const char* const>
 {
     static const std::vector s_extension_names{ []() -> std::vector<const char*> {
-        if (glfwInit() != GLFW_TRUE) {
-            return {};
-        }
+        init_glfw();
 
         uint32_t             count{};
         const char**         glfw_extension_names{ glfwGetRequiredInstanceExtensions(&count) };
-- 
GitLab