Feature guide » Platform support

Integration into windowing toolkits and creation of windowless contexts.

Platform namespace contains classes integrating Magnum engine into various toolkits, both windowed and windowless. Each class has slightly different dependencies and platform requirements, see documentation of Platform namespace and particular *Application classes for more information about building and usage with CMake.

All the classes have common API to achieve static polymorphism, so basically you can use different toolkits on different platforms and the only thing you need to change is the class name, everything else is the same. Basic usage is to subclass the chosen *Application class and implement required methods.

Windowed applications

Windowed applications provide a window and keyboard and mouse handling. The de-facto standard and most widely used toolkit is SDL2, which is implemented in Platform::Sdl2Application. As said above, the usage is similar for all toolkits, you must provide one-argument constructor and implement at least drawEvent() function. The class can be then used directly in main(), but for convenience and portability it's better to use MAGNUM_SDL2APPLICATION_MAIN() macro.

To simplify the porting, the library provides Platform::Application typedef and MAGNUM_APPLICATION_MAIN() macro (but only if only one application header is included, to avoid ambiguity). Changing the code to use different toolkit is then matter of replacing only the #include statement (and changing one line in CMake build script, as you see later).

Barebone application implementation which will just clear the window to dark blue color is shown in the following code listing.

#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Platform/GLContext.h>

using namespace Magnum;

class MyApplication: public Platform::Application {
    public:
        MyApplication(const Arguments& arguments);

    private:
        void drawEvent() override;
};

MyApplication::MyApplication(const Arguments& arguments): Platform::Application{arguments} {
    using namespace Math::Literals;
    /* Set clear color to dark blue */
    GL::Renderer::setClearColor(0x000066_rgbf);
}

void MyApplication::drawEvent() {
    /* Clear the window */
    GL::defaultFramebuffer.clear(GL::FramebufferClear::Color);

    /* The context is double-buffered, swap buffers */
    swapBuffers();
}

/* main() function implementation */
MAGNUM_APPLICATION_MAIN(MyApplication)

Responding to viewport size changes

By default the application doesn't respond to window size changes in any way, as the window has fixed size in most cases. To respond to size change for example by resizing the default framebuffer, you need to reimplement viewportEvent() function and pass the new size to the framebuffer:

class MyApplication: public Platform::Application {
    // ...

    private:
        void viewportEvent(ViewportEvent& event) override;
};

// ...

void MyApplication::viewportEvent(ViewportEvent& event) {
    GL::defaultFramebuffer.setViewport({{}, event.framebufferSize()});
}

Windowless applications

Windowless applications provide just a context for ofscreen rendering or performing tasks on GPU. There is not yet any platform-independent toolkit which could handle this in portable way, thus you have to use platform-specific ones. Magnum provides windowless applications for X11-based Unix, macOS and Windows. To make things simple, as an example we will use only Platform::WindowlessEglApplication, see link for bootstrap application below for fully portable example.

You need to implement just exec() function. The class can be then used directly in main(), but again, for convenience and portability it's better to use MAGNUM_WINDOWLESSEGLAPPLICATION_MAIN() macro.

Similarly as with windowed applications, to simplify the porting, the library provides Platform::WindowlessApplication typedef and MAGNUM_WINDOWLESSAPPLICATION_MAIN() macro, but only if just one windowless application header is included. Changing the code to use different toolkit is then matter of replacing only the #include statement. Aliases for windowless applications are separated from aliases for windowed applications, because projects commonly contain both graphics application and command-line tools (for data preparation etc.).

Barebone application which will just print out current OpenGL version and renderer string and exits is in the following code listing.

#include <Magnum/GL/Context.h>
#include <Magnum/Platform/WindowlessEglApplication.h>

using namespace Magnum;

class MyApplication: public Platform::WindowlessApplication {
    public:
        MyApplication(const Arguments& arguments);

        int exec() override;
};

MyApplication::MyApplication(const Arguments& arguments):
    Platform::WindowlessApplication{arguments} {}

int MyApplication::exec() {
    Debug{} << "OpenGL version:" << GL::Context::current().versionString();
    Debug{} << "OpenGL renderer:" << GL::Context::current().rendererString();

    /* Exit with success */
    return 0;
}

/* main() function implementation */
MAGNUM_WINDOWLESSAPPLICATION_MAIN(MyApplication)

Compilation with CMake

Barebone compilation consists just of finding Magnum library with, for example, Sdl2Application component, compilation of the executable and linking Magnum::Magnum and Magnum::Sdl2Application to it.

Again, to simplify porting, you can also use generic Magnum::Application aliases (or Magnum::WindowlessApplication for windowless applications), but only if only one application (windowless application) component is requested to avoid ambiguity. Changing the build script to use different toolkit is then matter of replacing only the requested *Application component (and one #include line in the actual code, as said above).

find_package(Magnum REQUIRED Sdl2Application)

add_executable(myapplication MyApplication.cpp)
target_link_libraries(myapplication
    Magnum::Magnum
    Magnum::Application)

Specifying configuration

By default the application is created with some reasonable defaults (e.g. window size 800x600 pixels). If you want something else, you can pass Configuration instance to application constructor. Using method chaining it can be done conveniently like this:

MyApplication::MyApplication(const Arguments& arguments):
    Platform::Application(arguments, Configuration{}
        .setTitle("My Application")
        .setSize({800, 600}))
{
    // ...
}

However, sometimes you would need to configure the application based on some configuration file or system introspection. In that case you can pass nullptr instead of Configuration instance and then specify it later with create():

MyApplication::MyApplication(const Arguments& arguments):
    Platform::Application{arguments, NoCreate}
{
    // ...

    create(Configuration{}
        .setTitle("My Application")
        .setSize(size));

    // ...
}

If the context creation in constructor or create() fails, the application exits. However, it is also possible to negotiate the context using tryCreate(). The only difference is that this function returns false instead of exiting. You can for example try enabling MSAA and if the context creation fails, fall back to no-AA rendering:

MyApplication::MyApplication(const Arguments& arguments):
    Platform::Application{arguments, NoCreate}
{
    // ...

    Configuration conf;
    conf.setTitle("My Application");
    GLConfiguration glConf;
    glConf.setSampleCount(16);

    if(!tryCreate(conf, glConf))
        create(conf, glConf.setSampleCount(0));

    // ...
}

Using custom platform toolkits

In case you want to use some not-yet-supported toolkit or you don't want to use the application wrappers in Platform namespace, you can initialize Magnum manually. First create OpenGL context and then create instance of Platform::GLContext class, which will take care of proper initialization and feature detection. The instance must be alive for whole application lifetime. Example main() function with manual initialization is in the following code listing.

int main() {
    // Create OpenGL context ...

    {
        /* Initialize Magnum */
        Platform::GLContext context;

        // Main loop ...

        /* Magnum context gets destroyed */
    }

    // Delete OpenGL context ...
}

On majority of platforms the Platform::GLContext class does GL function pointer loading using platform-specific APIs. In that case you also need to find particular *Context library, add its include dir and then link to it. These platform-specific libraries are available:

  • CglContext — CGL context (macOS)
  • EglContext — EGL context (everywhere except Emscripten)
  • GlxContext — GLX context (X11-based Unix)
  • WglContext — WGL context (Windows)

Systems not listed here (such as Emscripten) don't need any Context library, because dynamic function pointer loading is not available on these.

For example, when you create the OpenGL context using GLX, you need to find GlxContext component, and link to Magnum::GlxContext target. Similarly to application libraries, you can also use generic Magnum::Context target, providing you requested only one *Context component in the find_package() call. Complete example:

find_package(Magnum REQUIRED GlxContext)

add_executable(myapplication MyCustomApplication.cpp)
target_link_libraries(myapplication
    Magnum::Magnum
    Magnum::Context)

Manually managing windowless contexts

In case you need to manage windowless OpenGL contexts manually (for example to use Magnum for data processing in a thread or when having more than one OpenGL context), there is a possibility to directly use the context wrappers from windowless applications. Each Platform::Windowless*Application is accompanied by a Platform::Windowless*Context class that manages just GL context creation, making it current and destruction. Similarly to using custom platform toolkits above, the workflow is to first create a GL context instance, then making it current and finally instantiating the Platform::GLContext instance to initialize Magnum.

Similarly as with the applications, to simplify the porting, the library provides Platform::WindowlessGLContext typedef, but only if just one windowless application header is included.

int main(int argc, char** argv) {
    Platform::WindowlessGLContext glContext{{}};
    glContext.makeCurrent();
    Platform::GLContext context{argc, argv};

    // Your GL code ...

    /* Make another context current */
    eglMakeCurrent(display, surface, surface, anotherContext);

    // Someone else's code ...

    /* Make Magnum context current again */
    glContext.makeCurrent();

    // Your GL code again ...

    /* Magnum context gets destroyed */
    /* Windowless GL context gets destroyed */
}

The main purpose of windowless contexts is threaded OpenGL, used for example for background data processing. The workflow is to create the windowless context on the main thread, but make it current in the worker thread. This way the main thread state isn't affected so it can have any other GL context current (for example for the main application rendering). See also MAGNUM_BUILD_MULTITHREADED.

int main() {
    Platform::WindowlessGLContext glContext{{}};

    std::thread worker{[&glContext]{
        glContext.makeCurrent();
        Platform::GLContext context;

        // Use Magnum here ...
    }};

    // Independent main application code here ...

    worker.join();
}