Question

I am trying to update my camera's parameters based on my mouse movement in OpenGL. I am using GLFW. There is an predefined event handler in GLFW

glfwSetCursorPosCallback(window, mouseMoveCallback);

that i'm using to register the mouseMoveCallback() function. I have declared my Camera in a class and an instance of the Camera class is used in the program. The members in the Camera class are non-static but the mouseMoveCallback function is static. I know it is not possible for a static function to access non-static members. What is the best way I can update the members of the non-static instance of Camera's class?

I am able to gain the required functionality by using globals and using the mouseMoveCallback() function to update the globals and then reading the updated global values from the non-static member functions. But this can get ugly real quick when I want to add more parameters to read from, like keyboard inputs, etc. So I wanted to know if there is a better way of doing this

Was it helpful?

Solution

You can use glfwSet/GetWindowUserPointer to associate a user-defined pointer with a GLFWwindow object. Let's say you create a GLFWwindow pointed to by win, and a Camera object pointed to by cam - setup with:

...
glfwSetWindowUserPointer(win, cam);
glfwSetCursorPosCallback(win, mouseMoveCallback);
...

Since mouseMoveCallback is called from a C library, it has C linkage:

extern "C" void mouseMoveCallback (GLFWwindow *win, double x, double y)
{
    // get the associated user-data:
    Camera *cam = static_cast<Camera *>(glfwGetWindowUserPointer(win));

    // manipulate the associated Camera object:
    ...
}

OTHER TIPS

Your question requires you to decide which design to use to communicate to your object instances.

One design could be to create a global std::map of window handles as the key and object instance as the data. When the handle comes in, you search the map for the window handle and you can retrieve the object instance from there.

Another design is to see if the callback allows a "user parameter". If so, then you can attach the pointer to the instance to the user parameter. When the callback is invoked, you retrieve the instance from the "user parameter".

These are just two methods. There are others that I won't mention, but can be researched by doing a search for ways of "making an object-oriented wrapper for a 'C' interface".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top