TExcelTAD
Home › Game Engine Architecture in C++ › The Platform Layer: SDL3 and GLFW

The Platform Layer: SDL3 and GLFW

The platform layer is the only part of the engine that talks to the operating system directly: it creates the window and the graphics context or surface, pumps OS events, reads keyboards, mice and gamepads, provides a high-resolution timer, and finds writable folders. Everything above it sees engine types (KeyEvent, WindowResized), never HWND, NSWindow or SDL_Event.

Writing this layer per OS (Win32, Cocoa, X11, Wayland, Android, consoles) is a huge amount of edge-case work. Almost every small and medium engine uses a library instead:

Library What it gives you Notes
SDL3 windows, OpenGL/Vulkan/Metal surfaces, input (keyboard, mouse, gamepads with a large mapping database, touch, pens), audio devices, timers, file dialogs, threads, the GPU API SDL_GPU zlib license; desktop, mobile and the web; the 3.x API is stable since 3.2.0
GLFW windows, OpenGL/Vulkan contexts, keyboard, mouse, joysticks/gamepads small and focused; desktop only (Windows, macOS, X11, Wayland)
sokol_app window, 3D context, input, in one header pairs with sokol_gfx; also targets the web and mobile

This course uses SDL3 for the mini project. If you know SDL2, note that SDL3 renamed and changed a lot: events are SDL_EVENT_*, most functions return bool (true on success) instead of 0/negative, event.key.keysym.sym became event.key.key, SDL_GL_DeleteContext is now SDL_GL_DestroyContext, and SDL_GetKeyboardState returns const bool*. The official README-migration.md in the SDL repository lists every change.

An SDL3 window and event loop

cpp
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>   // include in the file that defines main(); handles WinMain and friends

int main(int argc, char* argv[]) {
    if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) {
        SDL_Log("SDL_Init failed: %s", SDL_GetError());
        return 1;
    }
    SDL_Window* window = SDL_CreateWindow("My Engine", 1280, 720,
                                          SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY);
    if (!window) {
        SDL_Log("SDL_CreateWindow failed: %s", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    bool running = true;
    Uint64 previous = SDL_GetTicksNS();
    while (running) {
        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            switch (e.type) {
            case SDL_EVENT_QUIT:
                running = false;
                break;
            case SDL_EVENT_KEY_DOWN:
                if (e.key.key == SDLK_ESCAPE) running = false;         // keycode: layout-dependent symbol
                if (!e.key.repeat && e.key.scancode == SDL_SCANCODE_SPACE) {
                    // first press only, OS key repeat ignored
                }
                break;
            case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
                // e.window.data1 x e.window.data2 is the new drawable size in pixels
                break;
            case SDL_EVENT_GAMEPAD_ADDED:
                SDL_OpenGamepad(e.gdevice.which);
                break;
            }
        }

        const bool* keys = SDL_GetKeyboardState(nullptr);   // indexed by SDL_Scancode
        float moveX = (keys[SDL_SCANCODE_D] ? 1.0f : 0.0f) - (keys[SDL_SCANCODE_A] ? 1.0f : 0.0f);

        Uint64 now = SDL_GetTicksNS();
        double dt = (now - previous) / 1e9;
        previous = now;
        // update(dt, moveX); render();
    }

    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

Three details matter in every engine:

  • Scancode vs keycode. A scancode is the physical key position (SDL_SCANCODE_W is the key left of E on a US layout, wherever the layout puts the letter); a keycode is the symbol the layout produces (SDLK_W). Bind movement to scancodes, so WASD stays a triangle on AZERTY keyboards, and show prompts using the keycode name (SDL_GetKeyName(SDL_GetKeyFromScancode(sc, SDL_KMOD_NONE, false))).
  • Window size vs pixel size. On high-DPI displays the window may be 1280×720 points but 2560×1440 pixels. Size framebuffers from SDL_GetWindowSizeInPixels or the SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED event, and UI from the content scale (SDL_GetWindowDisplayScale).
  • Key repeat. The OS sends repeated KEY_DOWN events while a key is held. Ignore them for gameplay (e.key.repeat), keep them for text fields.

SDL3's optional callback entry point

On the web and on mobile the OS, not your while loop, owns the frame. SDL3 offers an alternative entry point where SDL calls you instead. The same code then runs on every platform:

cpp
#define SDL_MAIN_USE_CALLBACKS 1
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>

struct App { SDL_Window* window = nullptr; Uint64 previous = 0; };

SDL_AppResult SDL_AppInit(void** appstate, int argc, char* argv[]) {
    if (!SDL_Init(SDL_INIT_VIDEO)) return SDL_APP_FAILURE;
    auto* app = new App;
    app->window = SDL_CreateWindow("My Engine", 1280, 720, SDL_WINDOW_RESIZABLE);
    if (!app->window) return SDL_APP_FAILURE;
    app->previous = SDL_GetTicksNS();
    *appstate = app;
    return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppEvent(void* appstate, SDL_Event* event) {
    if (event->type == SDL_EVENT_QUIT) return SDL_APP_SUCCESS;    // ends the program cleanly
    return SDL_APP_CONTINUE;
}

SDL_AppResult SDL_AppIterate(void* appstate) {                     // one frame
    auto* app = static_cast<App*>(appstate);
    Uint64 now = SDL_GetTicksNS();
    double dt = (now - app->previous) / 1e9;
    app->previous = now;
    // update(dt); render();
    return SDL_APP_CONTINUE;
}

void SDL_AppQuit(void* appstate, SDL_AppResult result) {
    auto* app = static_cast<App*>(appstate);
    if (app) { SDL_DestroyWindow(app->window); delete app; }
    // SDL calls SDL_Quit() for you after this returns
}

The same with GLFW

cpp
#include <GLFW/glfw3.h>

static void onKey(GLFWwindow* window, int key, int scancode, int action, int mods) {
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE);
}

int main() {
    if (!glfwInit()) return 1;
    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);        // for Vulkan; omit for OpenGL
    GLFWwindow* window = glfwCreateWindow(1280, 720, "My Engine", nullptr, nullptr);
    if (!window) { glfwTerminate(); return 1; }
    glfwSetKeyCallback(window, onKey);
    // glfwSetWindowUserPointer(window, &engine) lets callbacks reach your engine object

    double previous = glfwGetTime();
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();                                 // callbacks fire inside this call
        double now = glfwGetTime();
        double dt = now - previous;
        previous = now;
        int fbWidth, fbHeight;
        glfwGetFramebufferSize(window, &fbWidth, &fbHeight);   // pixels, not screen coordinates
        // update(dt); render();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
}

GLFW delivers input through callbacks during glfwPollEvents(), while SDL queues events for you to poll. Either way, the platform layer's job is to translate them into engine events and state.

A model: platform interface and a headless backend

The engine depends on a small interface, and each backend implements it. A headless backend that replays scripted events lets you run the whole engine in tests, on a build server and in this playground:

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <deque>
#include <memory>
#include <string>
#include <variant>

// ---- engine-side types: no SDL, no OS headers ----
enum class Key { W, A, S, D, Space, Escape };
struct KeyEvent { Key key; bool down; bool repeat; };
struct ResizeEvent { int widthPx, heightPx; };
struct QuitEvent {};
using Event = std::variant<KeyEvent, ResizeEvent, QuitEvent>;

class Platform {
public:
    virtual ~Platform() = default;
    virtual bool pollEvent(Event& out) = 0;
    virtual std::uint64_t ticksNs() const = 0;
    virtual void endFrame() = 0;               // present / swap / advance fake time
};

// ---- a backend: here a headless one that replays a script ----
class HeadlessPlatform : public Platform {
    std::deque<std::deque<Event>> frames_;     // events delivered per frame
    std::uint64_t ticks_ = 0;
public:
    explicit HeadlessPlatform(std::deque<std::deque<Event>> f) : frames_(std::move(f)) {}
    bool pollEvent(Event& out) override {
        if (frames_.empty() || frames_.front().empty()) return false;
        out = frames_.front().front();
        frames_.front().pop_front();
        return true;
    }
    std::uint64_t ticksNs() const override { return ticks_; }
    void endFrame() override {
        ticks_ += 16'666'667;                   // pretend vsync at 60 Hz
        if (!frames_.empty()) frames_.pop_front();
    }
};

const char* keyName(Key k) {
    const char* names[] = {"W", "A", "S", "D", "Space", "Escape"};
    return names[int(k)];
}

int main() {
    std::unique_ptr<Platform> platform = std::make_unique<HeadlessPlatform>(std::deque<std::deque<Event>>{
        {ResizeEvent{2560, 1440}},
        {KeyEvent{Key::W, true, false}},
        {KeyEvent{Key::W, true, true}, KeyEvent{Key::Space, true, false}},
        {KeyEvent{Key::W, false, false}},
        {KeyEvent{Key::Escape, true, false}, QuitEvent{}},
    });

    bool running = true, wHeld = false;
    float y = 0;
    for (int frame = 0; running && frame < 10; frame++) {
        Event e;
        while (platform->pollEvent(e)) {
            if (auto* k = std::get_if<KeyEvent>(&e)) {
                if (k->repeat) continue;                       // gameplay ignores OS key repeat
                std::printf("  frame %d: key %s %s\n", frame, keyName(k->key), k->down ? "down" : "up");
                if (k->key == Key::W) wHeld = k->down;
            } else if (auto* r = std::get_if<ResizeEvent>(&e)) {
                std::printf("  frame %d: resize framebuffers to %dx%d\n", frame, r->widthPx, r->heightPx);
            } else {
                std::printf("  frame %d: quit requested\n", frame);
                running = false;
            }
        }
        if (wHeld) y += 1.0f;
        platform->endFrame();
    }
    std::printf("stopped at %.1f ms, y = %.1f\n", platform->ticksNs() / 1e6, y);
}
  frame 0: resize framebuffers to 2560x1440
  frame 1: key W down
  frame 2: key Space down
  frame 3: key W up
  frame 4: key Escape down
  frame 4: quit requested
stopped at 83.3 ms, y = 2.0

A real SdlPlatform implements the same three functions with SDL_PollEvent, SDL_GetTicksNS and SDL_GL_SwapWindow, mapping SDL_SCANCODE_W to Key::W in one switch. That switch is the only place in the engine where SDL's key enum appears.

Tip: Keep the platform interface small and boring. A thin wrapper you fully understand beats a deep abstraction that tries to hide every platform difference and leaks anyway.

Test yourself

Which identifier should a WASD movement binding use so it works on AZERTY keyboards?

  1. The keycode (SDLK_W)
  2. The scancode (SDL_SCANCODE_W)
  3. The character typed
  4. The key name string

In SDL3, what does SDL_Init return on success?

  1. 0
  2. true
  3. a pointer
  4. SDL_APP_CONTINUE

What is the benefit of a headless platform backend?

  1. Faster rendering
  2. The engine can run in tests, on build servers and in replays without a window or GPU
  3. It replaces the OS
  4. It removes the need for input handling