Skip to content
Fjodor Schelichow edited this page Nov 9, 2017 · 1 revision

OpenGL context

If all you need is an OpenGL context it is sufficient to simply create an object of the Window class.

sgltk::Window window("Title", window_width, window_height, window_x_position, window_y_position, SDL_WINDOW_HIDDEN);

The last parameter is one or more SDL_WindowFlags OR'd together and is optional. The flags SDL_WINDOW_OPENGL and SDL_WINDOW_RESIZABLE are used automatically.

Window

If you want to have control over the window's behaviour, you will have to create a subclass of the Window class that overrides the display function that serves as a draw callback or one of the handle_* functions to react to user input or other events.

class MyWindow : public sgltk::Window {
    void display() {
        glClearColor(0, 0, 0, 1);
	glClearDepth(1.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }

    public:
        MyWindow(const std::string& title, int res_x, int res_y, int offset_x, int offset_y) 
            : sgltk::Window(title, res_x, res_y, offset_x, offset_y) {}
        ~MyWindow();
};

Main loop

Every new window that you open is unresponsive at first. Your application will have to enter a main loop and process the window's events. This can be done manually by calling poll_events from within a loop.

sgltk::Window window("Title", 1024, 768, 100, 100);
for(;;) {
    window.poll_events();
}

Alternatively you can use the main loop that is provided by the Window class itself by simply calling run.

sgltk::Window window("Title", 1024, 768, 100, 100);
window.run();

The run function also allows you to set a limit for the frames per second being drawn.

sgltk::Window window("Title", 1024, 768, 100, 100);
window.run(60); //60 fps

Handling events

Handling events is done from within the handle_* functions. All the appropriate handle_* functions will be called by the poll_events function whenever you call it manually or once per frame by the run function. All necessary event information are provided through function parameters or member variables of the Window class.

class MyWindow : public sgltk::Window {
    void handle_key_press(const std::string& key, bool pressed) {
        std::cout << key;
        if(pressed) {
            std::cout << " pressed";
        } else {
            std::cout << " released";
        }
        std::cout << std::endl;
    }

    void handle_resize() {
        std::cout << "The new window size is " << width << "x" << height << std::endl;
    }

    public:
        MyWindow(const std::string& title, int res_x, int res_y, int offset_x, int offset_y) 
            : sgltk::Window(title, res_x, res_y, offset_x, offset_y) {}
        ~MyWindow();
};

The key parameter of the handle_keyboard and handle_key_press functions is the key name SDL2 uses.

Clone this wiki locally