Engine Layers and Subsystems
Every engine, from a weekend project to Unreal, is organized in layers. Lower layers know nothing about higher ones. The renderer may use the memory system, but the memory system must never call the renderer. This one rule keeps an engine buildable, testable and portable.
A typical layer stack
Game (rules, levels, UI)
│
┌──────── Gameplay foundations ────────┐
│ ECS / scene, events, scripting │
├───────────────────────────────────────┤
│ Rendering Physics Audio Tools │ subsystems
├───────────────────────────────────────┤
│ Resources: loading, caching, reload │
├───────────────────────────────────────┤
│ Core: loop, time, logging, asserts, │
│ memory, containers, jobs, config │
├───────────────────────────────────────┤
│ Platform: window, input, files, │
│ threads, timers (SDL3, GLFW, OS) │
└───────────────────────────────────────┘
Operating system / GPU driver| Layer | Contains | Typical libraries |
|---|---|---|
| Platform | window, events, file I/O, high-resolution timer, dynamic libraries | SDL3, GLFW, the OS API |
| Core | game loop, logging, asserts, allocators, containers, string IDs, job system, config | mostly your own code, {fmt}, spdlog |
| Resources | asset registry, loading, reference counting, hot reload, serialization | your own code, cgltf, stb_image |
| Subsystems | renderer, physics, audio, animation, tools | OpenGL/Vulkan/sokol/bgfx, Jolt, miniaudio, Dear ImGui |
| Gameplay foundations | entities and components, scene graph, events, scripting | EnTT, flecs, sol2 |
The arrows only point down. When a lower layer needs to tell a higher one something ("the window was resized", "this texture was reloaded"), it does so through a callback, an event queue or a polled flag that the higher layer registers or reads. It never includes the higher layer's headers.
Tip: Enforce the rule with the build system. Make each layer its own CMake library target and link only downward (
target_link_libraries(renderer PUBLIC core platform)). A forbidden#includethen fails to compile instead of slowly turning the engine into one big knot.
Subsystem lifetime: start up in order, shut down in reverse
Subsystems depend on each other: the renderer needs the window, the resource cache needs the file system and the renderer (to create GPU textures), the audio system needs the file system. They must start in dependency order and stop in the reverse order, so nothing is destroyed while something above it still uses it.
C++ static constructors run in an unspecified order across translation units, so engines avoid global singletons with constructors and start subsystems explicitly. The simplest version is a hand-written list in main. A slightly more robust one lets each subsystem declare its dependencies and sorts them:
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include <vector>
struct Subsystem {
std::string name;
std::vector<std::string> deps;
};
int main() {
std::vector<Subsystem> all = {
{"renderer", {"window", "jobs"}},
{"audio", {"files"}},
{"resources", {"files", "renderer", "audio"}},
{"window", {"log"}},
{"files", {"log"}},
{"jobs", {"log"}},
{"log", {}},
{"game", {"resources", "renderer", "audio"}},
};
std::map<std::string, const Subsystem*> byName;
for (auto& s : all) byName[s.name] = &s;
std::vector<std::string> order;
std::set<std::string> done, visiting;
bool cycle = false;
// depth-first: start every dependency before the subsystem itself
auto visit = [&](auto&& self, const std::string& n) -> void {
if (done.count(n)) return;
if (visiting.count(n)) { cycle = true; return; }
visiting.insert(n);
for (auto& d : byName.at(n)->deps) self(self, d);
visiting.erase(n);
done.insert(n);
order.push_back(n);
};
for (auto& s : all) visit(visit, s.name);
if (cycle) { std::puts("dependency cycle!"); return 1; }
for (auto& n : order) std::printf("startup %s\n", n.c_str());
for (auto it = order.rbegin(); it != order.rend(); ++it) std::printf("shutdown %s\n", it->c_str());
}startup log
startup window
startup jobs
startup renderer
startup files
startup audio
startup resources
startup game
shutdown game
shutdown resources
shutdown audio
shutdown files
shutdown renderer
shutdown jobs
shutdown window
shutdown log
log starts first and stops last, so every other subsystem can log during its own startup and shutdown. game starts last and stops first. If someone adds a dependency that creates a cycle (log depending on renderer), the sort reports it immediately.
An engine as a set of explicit objects
Many engines wrap the started subsystems in one Engine object and pass references to whoever needs them, instead of using global singletons. Member destructors run in reverse declaration order, which gives the reverse shutdown for free:
#include <cstdio>
struct Log { Log() { std::puts("+log"); } ~Log() { std::puts("-log"); } };
struct Window { explicit Window(Log&) { std::puts("+window"); } ~Window() { std::puts("-window"); } };
struct Renderer { Renderer(Log&, Window&) { std::puts("+renderer"); } ~Renderer() { std::puts("-renderer"); } };
struct Audio { explicit Audio(Log&) { std::puts("+audio"); } ~Audio() { std::puts("-audio"); } };
struct Engine {
// declaration order = construction order; destruction runs bottom-up
Log log;
Window window{log};
Renderer renderer{log, window};
Audio audio{log};
};
int main() {
Engine engine;
std::puts("...running frames...");
}+log
+window
+renderer
+audio
...running frames...
-audio
-renderer
-window
-log
This pattern is easy to read: the startup order is simply the order of the lines. The one trap is passing a member that is declared later (Window window{renderer} above renderer), which hands over a reference to an object that is not constructed yet. Keep dependencies above their users, and let -Wall (which includes -Wreorder and -Wuninitialized) and the sanitizers catch slips.
Engine and game: who owns main?
There are two common shapes:
| Shape | How it works | Used by |
|---|---|---|
| Engine owns the loop | The engine has main, runs the loop and calls game callbacks (OnStart, OnUpdate) or systems registered by the game. |
Unity, Unreal, Godot, sokol_app, SDL3's main callbacks |
| Game owns the loop | The game has main and calls engine functions: platform.pollEvents(), world.update(dt), renderer.draw(). |
Libraries such as raylib, many custom engines |
"Game owns the loop" is simpler to debug and makes tests easy (a test is just a main that calls fewer things). "Engine owns the loop" fits platforms that own the loop themselves, such as the web and mobile, which is why SDL3 added an optional callback entry point. The Platform Layer lesson shows both in SDL3.
Keep the runtime and the tools apart
A level editor, an asset importer and a profiler UI are big, change often and pull in heavy libraries (a GLTF importer, a texture compressor, Dear ImGui with docking). Keep them out of the runtime layers: build them as separate targets that link the engine, and make the shipped game a target that does not. The runtime then loads only cooked, ready-to-use data. The Field Notes: Architecture lesson returns to this.
Test yourself
The resource cache needs to tell the game that a texture was reloaded. How should it do that without breaking the layering rule?
- Include the game's headers and call a game function
- Publish an event or call a callback the game registered
- Make the texture a global variable
- Restart the game
Why should subsystems shut down in the reverse order of startup?
- It is faster
- So nothing is destroyed while a subsystem started later still uses it
- C++ requires it for all objects
- To free memory in order of size
In the Engine struct example, what decides the construction order of the members?
- The order of the constructor calls in main
- The order in which the members are declared
- Alphabetical order
- The order of their destructors