Game Engine Exercises
Time to practise. Each exercise has a starter program that compiles and runs but has a bug or a TODO. Fix it, press ▶ Run, and compare the result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Each exercise mirrors one lesson. If you get stuck, reread the linked lesson before opening the solution.
| # | Exercise | Practises |
|---|---|---|
| 1 | Fixed step with a clamp | fixed timestep, accumulator, spiral-of-death clamp |
| 2 | Aligned arena | alignment math, linear allocators |
| 3 | Stale handles | generational handles |
| 4 | Swap-and-pop removal | sparse sets, keeping indices consistent |
| 5 | Overwriting history | ring buffers |
| 6 | Startup order | subsystem dependencies, depth-first topological sort |
| 7 | Dirty transforms | scene graphs, dirty flags |
Exercise 1: Fixed step with a clamp
The object moves at 2 units per second. The starter integrates with each frame's raw dt, so the 0.6 s hitch teleports it. Make it advance in fixed steps of 0.1 s through an accumulator, adding at most maxFrame (0.25 s) of time per frame. (Lesson: The Game Loop and Fixed Timestep.)
#include <cstdio>
int main() {
const double step = 0.1, maxFrame = 0.25;
const double frames[] = {0.1, 0.05, 0.15, 0.6, 0.1}; // seconds; 0.6 is a hitch
double x = 0, v = 2.0, accumulator = 0;
for (int f = 0; f < 5; f++) {
// TODO: add the clamped frame time to the accumulator and run fixed steps of `step`
(void)step; (void)maxFrame; (void)accumulator;
int steps = 1;
x += v * frames[f]; // variable timestep: depends on frame lengths
std::printf("frame %d: dt=%.2f steps=%d x=%.2f\n", f, frames[f], steps, x);
}
}frame 0: dt=0.10 steps=1 x=0.20
frame 1: dt=0.05 steps=1 x=0.30
frame 2: dt=0.15 steps=1 x=0.60
frame 3: dt=0.60 steps=1 x=1.80
frame 4: dt=0.10 steps=1 x=2.00
Expected output when solved:
frame 0: dt=0.10 steps=1 x=0.20
frame 1: dt=0.05 steps=0 x=0.20
frame 2: dt=0.15 steps=2 x=0.60
frame 3: dt=0.60 steps=2 x=1.00
frame 4: dt=0.10 steps=1 x=1.20Hint: Add
std::min(frames[f], maxFrame)to the accumulator, then loopwhile (accumulator >= step). Compare with a small epsilon: 0.05 + 0.15 is not exactly 0.2 in binary floating point.
Show solution
#include <algorithm>
#include <cstdio>
int main() {
const double step = 0.1, maxFrame = 0.25;
const double frames[] = {0.1, 0.05, 0.15, 0.6, 0.1}; // seconds; 0.6 is a hitch
double x = 0, v = 2.0, accumulator = 0;
for (int f = 0; f < 5; f++) {
accumulator += std::min(frames[f], maxFrame);
int steps = 0;
while (accumulator >= step - 1e-9) {
x += v * step;
accumulator -= step;
steps++;
}
std::printf("frame %d: dt=%.2f steps=%d x=%.2f\n", f, frames[f], steps, x);
}
}Exercise 2: Aligned arena
allocate hands out offsets without rounding them up, so the float and double land at misaligned offsets. Fix it so every allocation starts at a multiple of its alignment (all alignments are powers of two). (Lesson: Linear and Stack Allocators.)
#include <cstddef>
#include <cstdio>
struct Arena {
std::size_t offset = 0;
std::size_t allocate(std::size_t size, std::size_t align) {
(void)align; // TODO: round offset up to a multiple of align
std::size_t start = offset;
offset = start + size;
return start;
}
};
int main() {
Arena a;
struct { const char* what; std::size_t size, align; } requests[] = {
{"char[3]", 3, 1}, {"float", 4, 4}, {"double", 8, 8}, {"char", 1, 1}, {"Vec4 (align 16)", 16, 16}, {"int", 4, 4}};
for (auto& r : requests) {
std::size_t at = a.allocate(r.size, r.align);
std::printf("%-16s at offset %2zu %s\n", r.what, at, at % r.align == 0 ? "ok" : "MISALIGNED");
}
std::printf("used %zu bytes\n", a.offset);
}char[3] at offset 0 ok
float at offset 3 MISALIGNED
double at offset 7 MISALIGNED
char at offset 15 ok
Vec4 (align 16) at offset 16 ok
int at offset 32 ok
used 36 bytes
Expected output when solved:
char[3] at offset 0 ok
float at offset 4 ok
double at offset 8 ok
char at offset 16 ok
Vec4 (align 16) at offset 32 ok
int at offset 48 ok
used 52 bytesHint:
(offset + align - 1) & ~(align - 1)rounds up to the next multiple ofalign.
Show solution
#include <cstddef>
#include <cstdio>
struct Arena {
std::size_t offset = 0;
std::size_t allocate(std::size_t size, std::size_t align) {
std::size_t start = (offset + align - 1) & ~(align - 1);
offset = start + size;
return start;
}
};
int main() {
Arena a;
struct { const char* what; std::size_t size, align; } requests[] = {
{"char[3]", 3, 1}, {"float", 4, 4}, {"double", 8, 8}, {"char", 1, 1}, {"Vec4 (align 16)", 16, 16}, {"int", 4, 4}};
for (auto& r : requests) {
std::size_t at = a.allocate(r.size, r.align);
std::printf("%-16s at offset %2zu %s\n", r.what, at, at % r.align == 0 ? "ok" : "MISALIGNED");
}
std::printf("used %zu bytes\n", a.offset);
}Exercise 3: Stale handles
A missile's aim handle still points at the destroyed bat, but after the slot is reused it suddenly finds the wolf. Make get reject stale handles. (Lesson: Generational Handles.)
#include <cstdint>
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
struct Handle { std::uint32_t index, gen; };
struct Pool {
std::vector<std::string> names;
std::vector<std::uint32_t> gens;
std::vector<bool> alive;
Handle create(std::string n) {
for (std::uint32_t i = 0; i < names.size(); i++)
if (!alive[i]) { names[i] = n; alive[i] = true; return {i, gens[i]}; }
names.push_back(n); gens.push_back(1); alive.push_back(true);
return {std::uint32_t(names.size() - 1), 1};
}
void destroy(Handle h) {
if (!get(h)) return;
alive[h.index] = false;
gens[h.index]++;
}
const std::string* get(Handle h) const {
// TODO: also reject handles whose generation doesn't match the slot's
if (h.index >= names.size() || !alive[h.index]) return nullptr;
return &names[h.index];
}
};
int main() {
Pool pool;
Handle bat = pool.create("bat");
Handle rat = pool.create("rat");
Handle aim = bat;
pool.destroy(bat);
Handle wolf = pool.create("wolf");
for (auto [label, h] : {std::pair{"aim", aim}, std::pair{"rat", rat}, std::pair{"wolf", wolf}}) {
const std::string* s = pool.get(h);
std::printf("%-4s -> %s\n", label, s ? s->c_str() : "(dead)");
}
}aim -> wolf
rat -> rat
wolf -> wolf
Expected output when solved:
aim -> (dead)
rat -> rat
wolf -> wolfHint:
destroyalready increments the slot's generation.getonly has to compare it withh.gen.
Show solution
#include <cstdint>
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
struct Handle { std::uint32_t index, gen; };
struct Pool {
std::vector<std::string> names;
std::vector<std::uint32_t> gens;
std::vector<bool> alive;
Handle create(std::string n) {
for (std::uint32_t i = 0; i < names.size(); i++)
if (!alive[i]) { names[i] = n; alive[i] = true; return {i, gens[i]}; }
names.push_back(n); gens.push_back(1); alive.push_back(true);
return {std::uint32_t(names.size() - 1), 1};
}
void destroy(Handle h) {
if (!get(h)) return;
alive[h.index] = false;
gens[h.index]++;
}
const std::string* get(Handle h) const {
if (h.index >= names.size() || !alive[h.index] || gens[h.index] != h.gen) return nullptr;
return &names[h.index];
}
};
int main() {
Pool pool;
Handle bat = pool.create("bat");
Handle rat = pool.create("rat");
Handle aim = bat;
pool.destroy(bat);
Handle wolf = pool.create("wolf");
for (auto [label, h] : {std::pair{"aim", aim}, std::pair{"rat", rat}, std::pair{"wolf", wolf}}) {
const std::string* s = pool.get(h);
std::printf("%-4s -> %s\n", label, s ? s->c_str() : "(dead)");
}
}Exercise 4: Swap-and-pop removal
Removing components with vector::erase shifts the dense array, but the sparse array still holds the old positions: entity 2 now reports the wrong hit points and removing entity 3 deletes entity 4's data. Implement swap-and-pop. (Lesson: A Sparse-Set ECS.)
#include <cstdio>
#include <vector>
struct Health { int hp; };
struct Storage {
std::vector<int> sparse = std::vector<int>(8, -1);
std::vector<int> dense;
std::vector<Health> data;
void add(int e, Health h) { sparse[e] = int(dense.size()); dense.push_back(e); data.push_back(h); }
Health* get(int e) { return sparse[e] < 0 ? nullptr : &data[sparse[e]]; }
void remove(int e) {
// TODO: erase shifts later elements, but their sparse entries are not updated.
// Replace this with swap-and-pop and fix the moved element's sparse entry.
int i = sparse[e];
dense.erase(dense.begin() + i);
data.erase(data.begin() + i);
sparse[e] = -1;
}
};
int main() {
Storage s;
for (int e = 0; e < 5; e++) s.add(e, {100 + e * 10});
s.remove(1);
s.remove(3);
for (int e = 0; e < 5; e++) {
Health* h = s.get(e);
if (h) std::printf("entity %d: hp %d\n", e, h->hp);
else std::printf("entity %d: no Health\n", e);
}
std::printf("dense:");
for (int e : s.dense) std::printf(" %d", e);
std::printf("\n");
}entity 0: hp 100
entity 1: no Health
entity 2: hp 130
entity 3: no Health
entity 4: hp 140
dense: 0 2 3
Expected output when solved:
entity 0: hp 100
entity 1: no Health
entity 2: hp 120
entity 3: no Health
entity 4: hp 140
dense: 0 4 2Hint: Move the last element into the hole, then point the moved entity's
sparseentry at the hole before popping.
Show solution
#include <cstdio>
#include <vector>
struct Health { int hp; };
struct Storage {
std::vector<int> sparse = std::vector<int>(8, -1);
std::vector<int> dense;
std::vector<Health> data;
void add(int e, Health h) { sparse[e] = int(dense.size()); dense.push_back(e); data.push_back(h); }
Health* get(int e) { return sparse[e] < 0 ? nullptr : &data[sparse[e]]; }
void remove(int e) {
int i = sparse[e], last = int(dense.size()) - 1;
dense[i] = dense[last];
data[i] = data[last];
sparse[dense[i]] = i;
dense.pop_back();
data.pop_back();
sparse[e] = -1;
}
};
int main() {
Storage s;
for (int e = 0; e < 5; e++) s.add(e, {100 + e * 10});
s.remove(1);
s.remove(3);
for (int e = 0; e < 5; e++) {
Health* h = s.get(e);
if (h) std::printf("entity %d: hp %d\n", e, h->hp);
else std::printf("entity %d: no Health\n", e);
}
std::printf("dense:");
for (int e : s.dense) std::printf(" %d", e);
std::printf("\n");
}Exercise 5: Overwriting history
The frame history should always keep the four most recent values. When full, the starter refuses new values instead of dropping the oldest. (Lesson: Fixed-Capacity Containers and Ring Buffers.)
#include <cstdio>
struct History {
int data[4] = {};
unsigned head = 0, tail = 0;
unsigned size() const { return head - tail; }
void push(int v) {
if (size() == 4) return; // TODO: overwrite the oldest value instead
data[head++ % 4] = v;
}
int at(unsigned i) const { return data[(tail + i) % 4]; } // 0 = oldest
};
int main() {
History h;
for (int v = 1; v <= 6; v++) {
h.push(v * 100);
std::printf("after %d:", v * 100);
for (unsigned i = 0; i < h.size(); i++) std::printf(" %d", h.at(i));
std::printf("\n");
}
}after 100: 100
after 200: 100 200
after 300: 100 200 300
after 400: 100 200 300 400
after 500: 100 200 300 400
after 600: 100 200 300 400
Expected output when solved:
after 100: 100
after 200: 100 200
after 300: 100 200 300
after 400: 100 200 300 400
after 500: 200 300 400 500
after 600: 300 400 500 600Hint: When full, advance
tailby one before writing athead.
Show solution
#include <cstdio>
struct History {
int data[4] = {};
unsigned head = 0, tail = 0;
unsigned size() const { return head - tail; }
void push(int v) {
if (size() == 4) tail++; // drop the oldest
data[head++ % 4] = v;
}
int at(unsigned i) const { return data[(tail + i) % 4]; } // 0 = oldest
};
int main() {
History h;
for (int v = 1; v <= 6; v++) {
h.push(v * 100);
std::printf("after %d:", v * 100);
for (unsigned i = 0; i < h.size(); i++) std::printf(" %d", h.at(i));
std::printf("\n");
}
}Exercise 6: Startup order
Subsystems start in alphabetical order, so audio starts before log and files, and game before everything it needs. Start each subsystem after all its dependencies (each exactly once) and shut down in reverse. (Lesson: Engine Layers and Subsystems.)
#include <cstdio>
#include <functional>
#include <map>
#include <set>
#include <string>
#include <vector>
int main() {
std::map<std::string, std::vector<std::string>> deps = {
{"audio", {"files", "log"}}, {"files", {"log"}}, {"game", {"physics", "renderer", "audio"}},
{"log", {}}, {"physics", {"jobs"}}, {"jobs", {"log"}}, {"renderer", {"window", "jobs"}}, {"window", {"log"}},
};
std::vector<std::string> order;
std::set<std::string> done;
std::function<void(const std::string&)> visit = [&](const std::string& n) {
// TODO: start every dependency first (and each subsystem only once)
order.push_back(n);
};
for (auto& [name, _] : deps) visit(name);
std::printf("startup :");
for (auto& n : order) std::printf(" %s", n.c_str());
std::printf("\nshutdown:");
for (auto it = order.rbegin(); it != order.rend(); ++it) std::printf(" %s", it->c_str());
std::printf("\n");
}startup : audio files game jobs log physics renderer window
shutdown: window renderer physics log jobs game files audio
Expected output when solved:
startup : log files audio jobs physics window renderer game
shutdown: game renderer window physics jobs audio files logHint: Recursive depth-first search: visit the dependencies first, then append the subsystem. The
doneset prevents duplicates. (A full solution would also detect cycles, as in the Engine Layers lesson.)
Show solution
#include <cstdio>
#include <functional>
#include <map>
#include <set>
#include <string>
#include <vector>
int main() {
std::map<std::string, std::vector<std::string>> deps = {
{"audio", {"files", "log"}}, {"files", {"log"}}, {"game", {"physics", "renderer", "audio"}},
{"log", {}}, {"physics", {"jobs"}}, {"jobs", {"log"}}, {"renderer", {"window", "jobs"}}, {"window", {"log"}},
};
std::vector<std::string> order;
std::set<std::string> done;
std::function<void(const std::string&)> visit = [&](const std::string& n) {
if (done.count(n)) return;
done.insert(n);
for (auto& d : deps.at(n)) visit(d);
order.push_back(n);
};
for (auto& [name, _] : deps) visit(name);
std::printf("startup :");
for (auto& n : order) std::printf(" %s", n.c_str());
std::printf("\nshutdown:");
for (auto it = order.rbegin(); it != order.rend(); ++it) std::printf(" %s", it->c_str());
std::printf("\n");
}Exercise 7: Dirty transforms
Only the tank moves, yet every frame recomputes all five world transforms. Use the dirty flags that markDirty already sets so only the tank and its turret are recomputed. (Lesson: Scene Graph and Dirty Transforms.)
#include <cstdio>
#include <vector>
struct Node { int parent; float localX; float worldX = 0; bool dirty = true; };
int recomputed = 0;
void markDirty(std::vector<Node>& nodes, int i) {
nodes[i].dirty = true;
for (std::size_t c = 0; c < nodes.size(); c++)
if (nodes[c].parent == i) markDirty(nodes, int(c));
}
void update(std::vector<Node>& nodes) { // parents are stored before children
for (auto& n : nodes) {
// TODO: skip nodes that are not dirty
n.worldX = n.localX + (n.parent >= 0 ? nodes[n.parent].worldX : 0.0f);
n.dirty = false;
recomputed++;
}
}
int main() {
// 0 root, 1 tank (child of 0), 2 turret (child of 1), 3 tree (child of 0), 4 rock (child of 0)
std::vector<Node> nodes = {{-1, 0}, {0, 5}, {1, 1}, {0, 20}, {0, 30}};
update(nodes);
std::printf("frame 0: recomputed %d, turret at %.1f\n", recomputed, nodes[2].worldX);
for (int frame = 1; frame <= 3; frame++) {
recomputed = 0;
nodes[1].localX += 2; // only the tank moves
markDirty(nodes, 1);
update(nodes);
std::printf("frame %d: recomputed %d, turret at %.1f\n", frame, recomputed, nodes[2].worldX);
}
}frame 0: recomputed 5, turret at 6.0
frame 1: recomputed 5, turret at 8.0
frame 2: recomputed 5, turret at 10.0
frame 3: recomputed 5, turret at 12.0
Expected output when solved:
frame 0: recomputed 5, turret at 6.0
frame 1: recomputed 2, turret at 8.0
frame 2: recomputed 2, turret at 10.0
frame 3: recomputed 2, turret at 12.0Hint: In
update,continuewhen a node isn't dirty. It works because parents are stored before children, so a dirty parent is always updated before its children read it.
Show solution
#include <cstdio>
#include <vector>
struct Node { int parent; float localX; float worldX = 0; bool dirty = true; };
int recomputed = 0;
void markDirty(std::vector<Node>& nodes, int i) {
nodes[i].dirty = true;
for (std::size_t c = 0; c < nodes.size(); c++)
if (nodes[c].parent == i) markDirty(nodes, int(c));
}
void update(std::vector<Node>& nodes) { // parents are stored before children
for (auto& n : nodes) {
if (!n.dirty) continue;
n.worldX = n.localX + (n.parent >= 0 ? nodes[n.parent].worldX : 0.0f);
n.dirty = false;
recomputed++;
}
}
int main() {
// 0 root, 1 tank (child of 0), 2 turret (child of 1), 3 tree (child of 0), 4 rock (child of 0)
std::vector<Node> nodes = {{-1, 0}, {0, 5}, {1, 1}, {0, 20}, {0, 30}};
update(nodes);
std::printf("frame 0: recomputed %d, turret at %.1f\n", recomputed, nodes[2].worldX);
for (int frame = 1; frame <= 3; frame++) {
recomputed = 0;
nodes[1].localX += 2; // only the tank moves
markDirty(nodes, 1);
update(nodes);
std::printf("frame %d: recomputed %d, turret at %.1f\n", frame, recomputed, nodes[2].worldX);
}
}Test yourself
In Exercise 1, why does the 0.6 s hitch run only two fixed steps?
- The step size grows
- The frame time is clamped to 0.25 s before it is added, so at most two 0.1 s steps fit (plus the carried remainder)
- The accumulator is reset every frame
- Hitches are ignored completely
In Exercise 4, why does vector::erase break the sparse set?
- erase is too slow
- It shifts every later element down one position, but their sparse entries still hold the old positions
- erase frees the memory
- It changes entity IDs
Why does skipping clean nodes in Exercise 7 still give correct world positions?
- World positions never change
- Parents are stored before children and markDirty flags the whole moved subtree, so every node that needs updating is recomputed after its parent
- The turret has no parent
- Dirty flags are reset every frame