Jelajahi Sumber

REFACTOR: use GLFWwindow as a unique_ptr

Douglas Andreani 1 tahun lalu
induk
melakukan
9a81496d94
2 mengubah file dengan 16 tambahan dan 11 penghapusan
  1. 12 10
      src/game.cpp
  2. 4 1
      src/game.h

+ 12 - 10
src/game.cpp

@@ -24,31 +24,33 @@ Game::Game(int width, int height): m_window_width(width), m_window_height(height
 }
 
 Game::~Game() {
-   	glfwDestroyWindow(m_window);
+   	glfwDestroyWindow(*m_window);
 	glfwTerminate();
 }
 
 void Game::init() {
-    m_window = glfwCreateWindow(m_window_width
+    m_window = std::make_unique<GLFWwindow *>(glfwCreateWindow(
+          m_window_width
         , m_window_height
         , "My New Window"
         , NULL
-        , NULL);
+        , NULL)
+    );
 
 	if (!m_window) {
 		spdlog::error("Could not create GLFW Window.");
 		glfwTerminate();
 		return;
 	}
-	glfwMakeContextCurrent(m_window);
+	glfwMakeContextCurrent(*m_window);
 
 	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
 		spdlog::error("Failed to initialize GLAD");
 		return;
 	}
 
-	glfwSetKeyCallback(m_window, key_callback);
-	glfwSetFramebufferSizeCallback(m_window, framebuffer_size_callback);
+	glfwSetKeyCallback(*m_window, key_callback);
+	glfwSetFramebufferSizeCallback(*m_window, framebuffer_size_callback);
 
 
 	glViewport(0, 0, m_window_width, m_window_height);
@@ -69,7 +71,7 @@ void Game::run() {
     double deltaTime = 0.0f;
     double lastFrame = 0.0f;
 
-   	while (!glfwWindowShouldClose(m_window)) {
+   	while (!glfwWindowShouldClose(*m_window.get())) {
 
 
 		double currentFrame = glfwGetTime();
@@ -91,7 +93,7 @@ void Game::run() {
 		}
 		spdlog::warn("deltaTime {}", 1.0f/deltaTime);
 
-		glfwSwapBuffers(m_window);
+		glfwSwapBuffers(*m_window.get());
 	}
 
 }
@@ -101,6 +103,6 @@ void Game::add_renderer_object(Renderer obj) {
 }
 
 void Game::process_input() {
-	if (glfwGetKey(m_window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
-		glfwSetWindowShouldClose(m_window, true);
+	if (glfwGetKey(*m_window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
+		glfwSetWindowShouldClose(*m_window, true);
 }

+ 4 - 1
src/game.h

@@ -1,8 +1,11 @@
 #pragma once
+
 #define GLFW_INCLUDE_NONE
 #include <GLFW/glfw3.h>
 #include <glad/glad.h>
 #include <vector>
+#include <memory>
+
 #include "renderer.h"
 
 class Game {
@@ -18,7 +21,7 @@ public:
 
 private:
 
-    GLFWwindow* m_window = nullptr;
+    std::unique_ptr<GLFWwindow *> m_window;
     bool m_is_initialized = false;
     int m_window_height = 600;
     int m_window_width = 800;