18/21

8. Events

Events correspond to actions happening in an unpredictable manner. Typical events are users actions such as the use of the mouse and keyboard. For instance, clicking on the mouse can happen zero or multiple times, at a different time and different position. Programming in order to handle such events is called Event based programming.

The general objective of Event based programming is to link the reception of an event to an action, coded as a specific function. It usually corresponds to the following set of elements

  • A listener is set to way for a specific event.

  • Once an event happens, the listener triggers a response in calling an Action function.

The action function is often designated as a Callback Function, i.e. a function that is called by another one.

8. Events in GLFW

GLFW can handle listener on a set of input events.

The code setup a listener on the cursor position

glfwSetCursorPosCallback(window, cursor_position_callback );

In practice, every time the cursor is moved (ex. the mouse is moved, or touchpad activated), the user defined function cursor_position_callback is called.

In this case, the callback function (in our case cursor_position_callback) receives three parameters: the current window, the \(x\) and \(y\) position of the cursor within the window (in pixels).

Application to translation

The following code uses the detection of cursor position to model the translation of the point of view (or, similarly, the translation of the shape) in \((x,y)\) direction.

// Function called every time the mouse is moved
void cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
{
    const bool mouse_click_left   = (glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_LEFT )==GLFW_PRESS);
    const bool mouse_click_right  = (glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_RIGHT )==GLFW_PRESS);
    if(mouse_click_left)
    {
        tr_x += 0.0025*(xpos-x_prev);
        tr_y -= 0.0025*(ypos-y_prev);
    }

    x_prev = xpos;
    y_prev = ypos;
}
  • Execute the code and observe the translation using your mouse (keep your left click pressed, and move the mouse).

  • Note that the translation vector is passed as uniform parameter to the shader.