Configuration and Console Variables
Hard-coded constants are fine until someone needs to change them without recompiling: a tester turning off vsync, an artist tuning fog density, a player lowering shadow quality, a server admin raising the tick rate. Engines solve this with console variables (cvars): named, typed settings that can be read from config files, set from the command line, typed into a developer console, and saved.
Quake popularized them (sv_gravity 800), Unreal has IConsoleVariable (r.VSync, t.MaxFPS), Source has ConVar. The pattern is always the same.
Anatomy of a cvar
| Part | Example |
|---|---|
| Name, usually dotted by subsystem | r.vsync, phys.substeps, ui.scale |
| Type and default | bool, true |
| Range or allowed values | 1..8 |
| Help text | "Physics substeps per fixed step" |
| Flags | archive (save to the user's config), cheat (only in dev builds or with cheats on), read-only (set at startup only), requires restart |
| Change callback | the renderer recreates the swapchain when r.vsync changes |
Layered sources
Settings come from several places, and later layers override earlier ones:
defaults in code < engine.cfg (shipped) < platform.cfg < user.cfg (saved) < command line < consoleKeep the layers separate in your head: shipping a new engine.cfg with a patch must not wipe out the player's own user.cfg, and the save step writes only archive cvars whose values differ from the shipped defaults.
A cvar registry
#include <algorithm>
#include <cstdio>
#include <functional>
#include <map>
#include <sstream>
#include <string>
#include <variant>
using Value = std::variant<bool, int, float, std::string>;
enum Flags { None = 0, Archive = 1, Cheat = 2, ReadOnly = 4 };
struct CVar {
Value value, defaultValue;
float minV = 0, maxV = 0; // range for int/float when maxV > minV
int flags = None;
std::string help;
std::function<void(const CVar&)> onChange;
};
std::string toString(const Value& v) {
if (auto b = std::get_if<bool>(&v)) return *b ? "true" : "false";
if (auto i = std::get_if<int>(&v)) return std::to_string(*i);
if (auto f = std::get_if<float>(&v)) { char buf[32]; std::snprintf(buf, sizeof buf, "%g", *f); return buf; }
return std::get<std::string>(v);
}
struct Registry {
std::map<std::string, CVar> vars;
bool cheatsAllowed = false;
void add(const std::string& name, Value def, int flags, std::string help, float lo = 0, float hi = 0) {
vars[name] = CVar{def, def, lo, hi, flags, std::move(help), nullptr};
}
// Parses text into the cvar's existing type; returns an error message or "".
std::string set(const std::string& name, const std::string& text, bool startup = false) {
auto it = vars.find(name);
if (it == vars.end()) return "unknown cvar '" + name + "'";
CVar& cv = it->second;
if ((cv.flags & ReadOnly) && !startup) return name + " is read-only";
if ((cv.flags & Cheat) && !cheatsAllowed) return name + " is a cheat";
Value parsed;
try {
if (std::holds_alternative<bool>(cv.value)) {
if (text == "1" || text == "true") parsed = true;
else if (text == "0" || text == "false") parsed = false;
else return "expected a bool for " + name;
} else if (std::holds_alternative<int>(cv.value)) parsed = std::stoi(text);
else if (std::holds_alternative<float>(cv.value)) parsed = std::stof(text);
else parsed = text;
} catch (const std::exception&) { return "bad value '" + text + "' for " + name; }
if (cv.maxV > cv.minV) { // clamp numeric ranges
if (auto i = std::get_if<int>(&parsed)) *i = std::clamp(*i, int(cv.minV), int(cv.maxV));
if (auto f = std::get_if<float>(&parsed)) *f = std::clamp(*f, cv.minV, cv.maxV);
}
if (parsed == cv.value) return "";
cv.value = parsed;
if (cv.onChange) cv.onChange(cv);
return "";
}
// "name value" per line, '#' comments
void loadText(const char* source, const std::string& text, bool startup) {
std::istringstream in(text);
std::string line;
while (std::getline(in, line)) {
if (line.empty() || line[0] == '#') continue;
std::istringstream ls(line);
std::string name, value;
ls >> name >> value;
std::string err = set(name, value, startup);
if (!err.empty()) std::printf(" [%s] %s\n", source, err.c_str());
}
}
template <class T> T get(const std::string& name) const { return std::get<T>(vars.at(name).value); }
};
int main() {
Registry cv;
cv.add("r.vsync", true, Archive, "Wait for vertical blank");
cv.add("r.shadowQuality", 2, Archive, "0=off .. 3=ultra", 0, 3);
cv.add("phys.substeps", 2, None, "Physics substeps per fixed step", 1, 8);
cv.add("game.godMode", false, Cheat, "Player takes no damage");
cv.add("sys.threads", 4, ReadOnly, "Worker threads", 1, 64);
cv.vars["r.vsync"].onChange = [](const CVar& c) {
std::printf(" renderer: recreate swapchain, vsync=%s\n", toString(c.value).c_str());
};
std::puts("engine.cfg:");
cv.loadText("engine.cfg", "# shipped defaults\nphys.substeps 4\nsys.threads 8\n", true);
std::puts("user.cfg:");
cv.loadText("user.cfg", "r.vsync 0\nr.shadowQuality 9\nr.bloom 1\n", false);
std::puts("console:");
cv.loadText("console", "game.godMode 1\nsys.threads 2\nphys.substeps lots\n", false);
std::puts("final values:");
for (auto& [name, c] : cv.vars)
std::printf(" %-16s = %-6s (default %s)\n", name.c_str(), toString(c.value).c_str(),
toString(c.defaultValue).c_str());
std::printf("substeps as int: %d\n", cv.get<int>("phys.substeps"));
}engine.cfg:
user.cfg:
renderer: recreate swapchain, vsync=false
[user.cfg] unknown cvar 'r.bloom'
console:
[console] game.godMode is a cheat
[console] sys.threads is read-only
[console] bad value 'lots' for phys.substeps
final values:
game.godMode = false (default false)
phys.substeps = 4 (default 2)
r.shadowQuality = 3 (default 2)
r.vsync = false (default true)
sys.threads = 8 (default 4)
substeps as int: 4
Things to notice in the output:
r.shadowQuality 9is clamped to the allowed maximum of 3 rather than rejected. Whether to clamp or reject is a design choice; clamping is friendlier for hand-edited files.r.bloomdoesn't exist: the loader reports it and moves on. A config file from an older or newer version must never stop the game from starting.sys.threadscould be set byengine.cfgat startup but not from the console later;game.godModeis refused because cheats are off.- The
onChangecallback runs only when the value actually changes, which is where subsystems react (recreate the swapchain, resize the job pool).
Saving only what the player changed
When saving user.cfg, write archive cvars that differ from their defaults, nothing else. Otherwise every default value gets frozen into the player's file, and a patch that improves a default never reaches them:
#include <cstdio>
#include <map>
#include <string>
struct Setting { std::string value, shippedDefault; bool archive; };
int main() {
std::map<std::string, Setting> settings = {
{"r.vsync", {"false", "true", true}},
{"r.shadowQuality", {"2", "2", true}}, // unchanged: not saved
{"ui.scale", {"1.25", "1", true}},
{"phys.substeps", {"4", "2", false}}, // not archived: not saved
};
std::puts("# user.cfg (written by the game)");
for (auto& [name, s] : settings)
if (s.archive && s.value != s.shippedDefault) std::printf("%s %s\n", name.c_str(), s.value.c_str());
}# user.cfg (written by the game)
r.vsync false
ui.scale 1.25
Real engines and file formats
- Formats: key-value text (
.cfg,.ini) is easy to diff and hand-edit. JSON (withnlohmann/jsonorsimdjson), TOML (toml++) and YAML are common for tools. Avoid binary config: it can't be fixed by hand when it breaks. - Command line: accept
+set r.vsync 0or-r.vsync=0style arguments, so automated tests and benchmark scripts can configure a run without touching files. - Platform defaults: a
platform.cfgper target (Steam Deck, console, low-end PC) is a cheap way to ship sensible presets. - Where to save: the user's writable config folder, not the install directory. SDL3's
SDL_GetPrefPath(org, app)returns a per-user, per-app writable path on every platform.
// SDL3: a writable per-user folder, e.g. %APPDATA%\MyStudio\MyGame\ on Windows
char* prefPath = SDL_GetPrefPath("MyStudio", "MyGame");
if (prefPath) {
std::string userCfg = std::string(prefPath) + "user.cfg";
SDL_free(prefPath);
// ... load or save userCfg
}Test yourself
Why should user.cfg contain only archive cvars that differ from the shipped defaults?
- To make the file smaller only
- So later patches that change defaults still reach players who never touched those settings
- Because unchanged values cannot be parsed
- Because defaults are stored in the GPU
A config file contains a cvar name the engine doesn't know. What should the loader do?
- Refuse to start
- Report it and continue loading the rest
- Create a new cvar with that name
- Delete the file
Where does a subsystem react to a cvar change, such as rebuilding the swapchain when vsync flips?
- In the config file parser
- In a change callback (or by polling a changed flag) registered by that subsystem
- In main()
- Nowhere; changes need a restart