Skip to content

Instantly share code, notes, and snippets.

@rohit-kumar-j
Created December 30, 2022 13:55
Show Gist options
  • Save rohit-kumar-j/6e80cc38bb2215fb0e3329c5a7d72680 to your computer and use it in GitHub Desktop.
Save rohit-kumar-j/6e80cc38bb2215fb0e3329c5a7d72680 to your computer and use it in GitHub Desktop.
Multiple Window Handling wrapper class : header file for C++
// Derived from: GLFW call to non-static class function in static key_callback
// https://stackoverflow.com/a/62692209/14376181
//
#ifndef ENV_H
#define ENV_H
#include <GLFW/glfw3.h>
#include <direct.h>
#include <filesystem>
#include <iostream>
class Viewer {
public:
GLFWwindow* window;
Viewer(std::string title) {
glfwInit();
window = glfwCreateWindow(640, 480, title.c_str(), NULL, NULL);
glfwMakeContextCurrent(window);
}
static void keyCallbackWrapper(GLFWwindow* window, int key, int scancode, int action, int mods) {
Viewer* viewer = static_cast<Viewer*>(glfwGetWindowUserPointer(window));
viewer->keyCallback(window, key, scancode, action, mods);
}
void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
// basic window handling
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
std::cout << "exiting..." << std::endl;
glfwSetWindowShouldClose(window, GL_TRUE);
}
if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {
std::cout << "Space bar..." << std::endl;
}
}
};
class Env : public Viewer {
public:
Env(std::string title) : Viewer(title) {
// my viewer specific state gets initialized here
glfwSetWindowUserPointer(this->window, this);
glfwSetKeyCallback(this->window, Viewer::keyCallbackWrapper);
};
void RenderLoop() {
while (!glfwWindowShouldClose(this->window)) {
// update function gets called here
update();
glfwPollEvents();
glfwSwapBuffers(this->window);
}
glfwTerminate();
}
void update(){
// do something while the window is not closed...
}
};
#endif // ENV_H
// Example usage
int main(){
Env env("My Window");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment