TExcelTAD
Home › Game Engine Architecture in C++ › Graphics APIs: OpenGL, sokol and bgfx

Graphics APIs: OpenGL, sokol and bgfx

The renderer is the one engine layer where you must pick a lower-level library on day one. The choices fall into three groups:

Option What it is Good for
OpenGL 3.3+ core the classic cross-vendor API; immediate, driver-managed state learning, small engines, the mini project of this course
sokol_gfx a small C header-only wrapper over GL, Metal, D3D11, WebGPU tiny portable engines, web builds, keeping code short
bgfx a mature C++ rendering library over D3D11/12, Metal, Vulkan, GL, GLES shipping on many platforms without writing backends
Vulkan / D3D12 / Metal explicit APIs: you manage memory, sync and command buffers full control, large engines; see Vulkan

Whatever you choose, keep it behind a thin rendering interface inside the engine (an RHI, "render hardware interface"). Thin means: buffers, textures, pipelines, passes and draws. It does not mean wrapping every API call one-to-one, and it does not mean designing for five backends before you ship one.

A thin interface, modelled

The model below shows the shape of such an interface: the engine's renderer only talks to Device. One backend prints what it would ask OpenGL to do; a null backend (useful for servers and tests) only counts calls.

cpp · try it yourself
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct BufferId { int id; };
struct PipelineId { int id; };

class Device {
public:
    virtual ~Device() = default;
    virtual BufferId createVertexBuffer(const std::vector<float>& data) = 0;
    virtual PipelineId createPipeline(const std::string& shader) = 0;
    virtual void beginPass(float r, float g, float b) = 0;
    virtual void draw(PipelineId p, BufferId vb, int vertexCount) = 0;
    virtual void endPass() = 0;
};

class GlLogDevice : public Device {
    int nextId = 1;
public:
    BufferId createVertexBuffer(const std::vector<float>& data) override {
        std::cout << "glGenBuffers -> " << nextId << "; glBufferData(" << data.size() * sizeof(float) << " bytes)\n";
        return {nextId++};
    }
    PipelineId createPipeline(const std::string& shader) override {
        std::cout << "glCreateProgram -> " << nextId << " (" << shader << ")\n";
        return {nextId++};
    }
    void beginPass(float r, float g, float b) override {
        std::cout << "glClearColor(" << r << ", " << g << ", " << b << ", 1); glClear\n";
    }
    void draw(PipelineId p, BufferId vb, int n) override {
        std::cout << "glUseProgram(" << p.id << "); glBindVertexArray(vao of " << vb.id << "); glDrawArrays(GL_TRIANGLES, 0, " << n << ")\n";
    }
    void endPass() override { std::cout << "SDL_GL_SwapWindow\n"; }
};

class NullDevice : public Device {
public:
    int calls = 0, vertices = 0;
    BufferId createVertexBuffer(const std::vector<float>&) override { calls++; return {calls}; }
    PipelineId createPipeline(const std::string&) override { calls++; return {calls}; }
    void beginPass(float, float, float) override { calls++; }
    void draw(PipelineId, BufferId, int n) override { calls++; vertices += n; }
    void endPass() override { calls++; }
};

void renderFrame(Device& dev, PipelineId pip, BufferId tri) {      // engine code: backend-agnostic
    dev.beginPass(0.1f, 0.1f, 0.2f);
    dev.draw(pip, tri, 3);
    dev.endPass();
}

int main() {
    std::vector<float> triangle = {0, 0.5f, 0,  0.5f, -0.5f, 0,  -0.5f, -0.5f, 0};

    GlLogDevice gl;
    PipelineId pip = gl.createPipeline("triangle.vert + triangle.frag");
    BufferId vb = gl.createVertexBuffer(triangle);
    renderFrame(gl, pip, vb);

    NullDevice null;
    PipelineId p2 = null.createPipeline("triangle");
    BufferId b2 = null.createVertexBuffer(triangle);
    for (int frame = 0; frame < 60; frame++) renderFrame(null, p2, b2);
    std::cout << "null device: " << null.calls << " calls, " << null.vertices << " vertices in 60 frames\n";
}
glCreateProgram -> 1 (triangle.vert + triangle.frag)
glGenBuffers -> 2; glBufferData(36 bytes)
glClearColor(0.1, 0.1, 0.2, 1); glClear
glUseProgram(1); glBindVertexArray(vao of 2); glDrawArrays(GL_TRIANGLES, 0, 3)
SDL_GL_SwapWindow
null device: 182 calls, 180 vertices in 60 frames

A virtual call per draw is fine at this level of abstraction (a few thousand per frame). If the backend is chosen at compile time anyway, a plain class per platform selected with the build system works too and avoids the indirection.

OpenGL with SDL3 and glad

SDL3 creates the window and the GL context; a loader such as glad fetches the GL function pointers. vcpkg's glad port is glad 1 (features like gl-api-33 select the version), so the loader call is gladLoadGLLoader. This is the path the mini project uses:

cpp
#include <SDL3/SDL.h>
#include <glad/glad.h>

SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_Window* window = SDL_CreateWindow("engine", 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
SDL_GLContext ctx = SDL_GL_CreateContext(window);
if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { /* report and quit */ }
SDL_GL_SetSwapInterval(1);                                   // vsync

GLuint vao, vbo;
glGenVertexArrays(1, &vao);                                  // core profile requires a VAO
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// each frame:
glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
SDL_GL_SwapWindow(window);
// shutdown: SDL_GL_DestroyContext(ctx); SDL_DestroyWindow(window); SDL_Quit();

macOS caps OpenGL at 4.1 and Apple has deprecated it; it still runs there with SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG. For a long-lived engine that must run on Apple hardware, prefer one of the libraries below or Metal.

sokol_gfx

sokol is a set of single-file C headers by Andre Weissflog. sokol_app.h owns the window and the main loop through callbacks, sokol_gfx.h is the 3D API, sokol_glue.h connects the two. Shaders are written once in annotated GLSL and cross-compiled to every backend by the sokol-shdc tool, which generates a C header with triangle_shader_desc() and ATTR_… constants. Take the headers straight from the GitHub repository (the vcpkg port lags far behind) and define SOKOL_IMPL plus a backend such as SOKOL_GLCORE, SOKOL_METAL, SOKOL_D3D11 or SOKOL_WGPU in one source file.

glsl
@vs vs
in vec4 position;
in vec4 color0;
out vec4 color;
void main() { gl_Position = position; color = color0; }
@end

@fs fs
in vec4 color;
out vec4 frag_color;
void main() { frag_color = color; }
@end

@program triangle vs fs
c
static void init(void) {
    sg_setup(&(sg_desc){ .environment = sglue_environment(), .logger.func = slog_func });
    float vertices[] = { 0.0f, 0.5f, 0.5f,  1, 0, 0, 1,
                         0.5f, -0.5f, 0.5f, 0, 1, 0, 1,
                        -0.5f, -0.5f, 0.5f, 0, 0, 1, 1 };
    state.bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc){ .data = SG_RANGE(vertices) });
    state.pip = sg_make_pipeline(&(sg_pipeline_desc){
        .shader = sg_make_shader(triangle_shader_desc(sg_query_backend())),
        .layout.attrs = { [ATTR_triangle_position].format = SG_VERTEXFORMAT_FLOAT3,
                          [ATTR_triangle_color0].format   = SG_VERTEXFORMAT_FLOAT4 },
    });
}
static void frame(void) {
    sg_begin_pass(&(sg_pass){ .action = state.pass_action, .swapchain = sglue_swapchain() });
    sg_apply_pipeline(state.pip);
    sg_apply_bindings(&state.bind);
    sg_draw(0, 3, 1);
    sg_end_pass();
    sg_commit();
}
sapp_desc sokol_main(int argc, char* argv[]) {
    return (sapp_desc){ .init_cb = init, .frame_cb = frame, .cleanup_cb = sg_shutdown,
                        .width = 640, .height = 480, .window_title = "triangle", .logger.func = slog_func };
}

The designated initialisers are C99; in C++ (C++20 designated initialisers must follow declaration order and cannot use array designators) many people keep the sokol-facing code in .c files or fill structs field by field. sokol's API changes now and then; read the change log at the top of sokol_gfx.h when you update.

bgfx

bgfx (Branimir Karadžić) takes a native window handle and does everything else, including draw sorting: you submit to numbered views (think passes) with a depth, and bgfx builds and sorts the sort keys for you. It runs rendering on its own thread unless you call bgfx::renderFrame() before bgfx::init to stay single-threaded. Shaders use bgfx's GLSL-like language compiled offline by shaderc.

cpp
#include <bgfx/bgfx.h>

SDL_PropertiesID props = SDL_GetWindowProperties(window);
bgfx::Init init;
init.type = bgfx::RendererType::Count;                       // let bgfx choose the best backend
#if defined(_WIN32)
init.swapChain.nwh = SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr);
#endif                                                       // (other platforms: Cocoa / X11 / Wayland handles)
init.swapChain.width = 1280;
init.swapChain.height = 720;
init.reset = BGFX_RESET_VSYNC;
bgfx::init(init);
bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x303030ff, 1.0f, 0);

// each frame:
bgfx::setViewRect(0, 0, 0, 1280, 720);
bgfx::touch(0);                                              // make sure view 0 is cleared even with no draws
bgfx::setVertexBuffer(0, vbh);
bgfx::setIndexBuffer(ibh);
bgfx::setState(BGFX_STATE_DEFAULT);
bgfx::submit(0, program);
bgfx::frame();
// shutdown: destroy handles, then bgfx::shutdown();

Note: This is the current bgfx Init layout (init.swapChain.nwh, .width, .height, init.reset). Older releases, including some package-manager builds, use init.platformData.nwh and init.resolution.width/height/reset instead. Check bgfx.h of the version you build against.

Choosing

Learning graphics: OpenGL, because every tutorial and debugger supports it. A portable small engine or a web build: sokol. Shipping a cross-platform game with a custom engine and a small team: bgfx, or an explicit API only if you have the people to maintain it. The shading language side is covered in Shaders & Graphics Programming.

Test yourself

What does a loader such as glad do in an OpenGL program?

  1. Compiles shaders
  2. Fetches OpenGL function pointers from the driver after a context exists
  3. Creates the window
  4. Converts GLSL to SPIR-V

What does sokol-shdc produce?

  1. A window
  2. A C header with shader descriptions for each backend, generated from annotated GLSL
  3. SPIR-V for Vulkan only
  4. A texture atlas

In bgfx, what is a view?

  1. A camera matrix only
  2. A numbered bucket of draws with its own clear, rect and transforms, roughly a render pass
  3. A window
  4. A shader stage