Settings and saves
Settings and progress are your game’s data. Labrador’s asset loaders read content; they do not choose a save location or write a save format. Keep that code in your game, alongside the values it understands. This example writes a small JSON settings file with a version and a volume from 0 to 100. The same file-writing code works on Windows and in Emscripten’s virtual filesystem. If a build fails after you add it, Read a build error shows how to read the error. Save settings in your game writes and reads a settings file in the starter project, step by step. For version migration, retained previous files and explicit retry after a failure, follow Recover a failed save.
Apply settings to the running game
Section titled “Apply settings to the running game”A setting’s stored value and the platform’s current state can differ. The components gallery requests only Windowed or Full screen: Windows full screen is already a borderless window, so there is no separate third mode.
Window mode
Section titled “Window mode”The row’s callback calls Application::set_fullscreen. Initialization then
seeds the row from fullscreen():
const std::vector<std::wstring> window_modes = { L"Windowed", L"Full screen" };this->window_mode_ = this->scene_->add(std::make_unique<OptionRow>( "window", L"Window", window_modes, windowed_choice, [this, window_modes](size_t index) { this->app_->set_fullscreen(index == full_screen_choice); this->set_status(L"Window mode requested: " + window_modes[index]); }));this->window_mode_->set_index(this->app_->fullscreen() ? full_screen_choice : windowed_choice);samples/components/gallery_state.cpp, lines 209–221 at f525bc6
windowed_choice and full_screen_choice are the row’s two positions, named once
at the top of the file so the callback and both re-syncs agree on which is which.
fullscreen() reports the requested mode until the platform says otherwise.
A browser request can be deferred to an activating input event or refused,
and the player can leave full screen externally. The status line therefore
describes a request. The gallery reads the current report every tick:
void GalleryState::update(float dt){ this->update_cursor(); // A browser can refuse a request or leave full screen externally. // set_index follows that report without calling the request callback. this->window_mode_->set_index(this->app_->fullscreen() ? full_screen_choice : windowed_choice);samples/components/gallery_state.cpp, lines 377–383 at f525bc6
OptionRow::set_index changes the displayed choice without calling its
callback, so re-sync does not issue another request. The gallery keeps its
Escape/B quit binding; your game chooses how leaving full screen and quitting
fit its own controls.
Volume slider callbacks
Section titled “Volume slider callbacks”The gallery’s volume sliders illustrate callbacks and load no audio. In a
game with the audio sample’s required tones bank
already loaded, create music/effects groups in the Application’s
AudioResources and assign sounds through its SoundBank at load time:
const labrador::SoundGroupHandle music = audio->add_sound_group("music");const labrador::SoundGroupHandle effects = audio->add_sound_group("effects");bank->set_effect_group(bank->resolve_effect("drone_loop"), music);bank->set_wave_group(bank->resolve_wave("ping"), effects);bank->set_wave_group(bank->resolve_wave("chime"), effects);audio->set_group_volume(music, 0.7f);audio->set_group_volume(effects, 1.0f);Include engine/audio/audio_resources.h and engine/audio/sound_bank.h;
app here points to the Application. Create each group once, then keep its
handle or resolve it by name: add_sound_group throws for a name already added, and a state’s
init() runs again each time the game makes that state again. A group spans banks, so assign
any other banks’ music/effects to those same handles. In a starter project these lines need two
guides done first: Play sounds from an XWB bank loads the tones bank,
and Copy the components into your game copies the slider.
An effects volume in the starter project below puts
these lines and the slider’s into the starter’s state, with its whole init().
For a copied slider ranging from 0 to 100, pass this as its on_change
callback, in place of the gallery’s status-only callback:
const components::Slider::Changed effects_changed = [audio, effects](int value){ audio->set_group_volume(effects, static_cast<float>(value) / 100.0f);};Use the copied slider’s namespace and include path in your game
(samples/components/slider.h in this checkout). The music slider uses the
same scaling with the music handle. Set the initial group levels to match the
sliders too: Slider::set_value also updates silently.
A play level of 0.8f in an effects group set to 0.5f reaches the device
as 0.4f; no second volume bus is needed. A playing or paused retained effect
takes a group change immediately, a stopped effect takes it at its next play,
and a one-shot already playing keeps its old level while the next one takes
the new level. A sound assigned to no group remains at full group volume.
Keep the AudioResources and its bank alive longer than callbacks borrowing
them, as the gallery does for its Application services.
An effects volume in the starter project
Section titled “An effects volume in the starter project”This puts the lines above into the starter’s HelloState, as a third row, Effects, under
the two rows of Copy the components into your game. It needs
that page’s steps 1 to 5 and Play sounds from an XWB bank’s part 1 done
first: P plays ping, and the screen has the Colour and Speed rows. It takes about
ten minutes. The commands run in the x64 Native Tools Command Prompt, in C:\dev\mygame.
-
Keep a place for the row. Open the state’s header:
Terminal window notepad game\states\hello_state.hSearch for
speed_row_ = nullptr;and add a line after it, so the two read:components::Slider* speed_row_ = nullptr;components::Slider* volume_row_ = nullptr;Save and close Notepad.
-
Make the group and the row in
init(). Open the state’s code:Terminal window notepad game\states\hello_state.cppSearch for
#include "engine/core/state_context.h"and add a line above it, so the two read:#include "engine/audio/audio_resources.h"#include "engine/core/state_context.h"Then search for
I and K choose a row.You are at the help line under the rows, and the speed row’s last line is just above it. Select from the empty line after the speed row down to the end of the help line, these lines:L"I and K choose a row. J and L change it.", font_name,and paste these in their place:
// The effects volume: a group for the game's short sounds, with ping in// it, and a slider from 0 to 100 that sets the group's volume.const SoundGroupHandle effects = audio->add_sound_group("effects");this->tones_->set_wave_group(this->ping_, effects);this->volume_row_ = this->scene_->add(std::make_unique<components::Slider>("volume", L"Effects",resources->resolve_texture(white_texture_name), resources,[audio, effects](int value){audio->set_group_volume(effects,static_cast<float>(value) / 100.0f);}));L"I and K choose a row. J and L change it.", font_name,The help line moves down 40 pixels, from
104.0fto144.0f, to make room. A new group starts at volume 1, full, which matches the slider’s start of 100.set_wave_groupputspingin the group; it usestones_andping_, which the sound page’s lines near the top ofinit()have already set, so these lines must come after them, as they do here. The slider’s last argument is the code it runs on each change: it sets the group’s volume to the slider’s value over 100, so 50 plays every sound in the group at half its level.Then search for
this->focus_.add(this->speed_row_);and add a line after it, so the two read:this->focus_.add(this->speed_row_);this->focus_.add(this->volume_row_); -
Send J and L to the row. Still in
hello_state.cpp, search forthis->speed_row_->adjust(change);. After the}under it, add anelse iffor the new row, so the end of that part reads:else if (this->focus_.focused(0) == this->speed_row_){this->speed_row_->adjust(change);}else if (this->focus_.focused(0) == this->volume_row_){this->volume_row_->adjust(change);}Save and close Notepad.
-
Build, test and run:
Terminal window cmake --build --preset x64-debug && ctest --preset x64-debug && out\build\x64-debug\game\MyGame.exehello_state.cppandmain.cppare compiled again, and the tests pass as before; with them it took about 3 seconds. A third row, Effects, with a full bar and 100, is under Speed, and the help line is under it. Press K twice to move the cursor to it, then J: each press takes 10 away. At 50, P playspingat half its level; at 0 it is silent. Pressing L brings it back.
The whole of init() is then, with the sound page’s two lines near the top, the components
page’s rows, and this section’s group, row and focus_ line:
void HelloState::init(){ this->app_->resolution_manager()->resolution_vec(); this->motion_.centre = Vector2F(resolution.x * 0.5f - 120.0f, resolution.y * 0.5f);
this->tones_ = this->app_->audio_resources()->sound_bank("tones"); this->ping_ = this->tones_->resolve_wave("ping");
// No thread pool and no partitioner: those are the scene's per-view // fan-out, and one view does not need one.
L"Hello from the engine.", font_name, this->motion_.centre, resources,
this->hint_ = this->scene_->add(std::make_unique<Label>( L"Left stick, arrows or WASD move it. B or Escape asks to quit. Touch shows a marker.", font_name, Vector2F(24.0f, resolution.y - 40.0f), resources, labrador::Colour::dark_gray));
// Two rows from game/components, at the top left: the greeting's colour // and its speed, in percent. The slider's bar is drawn with the engine's // own white texture. this->colour_row_ = this->scene_->add( std::make_unique<components::OptionRow>("colour", L"Colour", std::vector<std::wstring>{ L"White", L"Gold", L"Coral", L"Green" }, 0, Vector2F(24.0f, 24.0f), 160.0f, font_name, resources, [this](size_t index) { this->greeting_->set_colour(greeting_colour(index)); }));
this->speed_row_ = this->scene_->add( std::make_unique<components::Slider>("speed", L"Speed", 0, 200, 25, 100, Vector2F(24.0f, 64.0f), resources->resolve_texture(white_texture_name), resources));
// The effects volume: a group for the game's short sounds, with ping in // it, and a slider from 0 to 100 that sets the group's volume. const SoundGroupHandle effects = audio->add_sound_group("effects"); this->tones_->set_wave_group(this->ping_, effects);
this->volume_row_ = this->scene_->add( std::make_unique<components::Slider>("volume", L"Effects", 0, 100, 10, 100, Vector2F(24.0f, 104.0f), RectangleF(160.0f, 108.0f, 200.0f, 10.0f), font_name, resources->resolve_texture(white_texture_name), resources, [audio, effects](int value) { audio->set_group_volume(effects, static_cast<float>(value) / 100.0f); }));
this->scene_->add(std::make_unique<Label>( L"I and K choose a row. J and L change it.", font_name, Vector2F(24.0f, 144.0f), resources, labrador::Colour::dark_gray));
// The cursor starts on the first row added. this->focus_.add(this->colour_row_); this->focus_.add(this->speed_row_); this->focus_.add(this->volume_row_);
for (Label*& marker : this->touch_markers_) { marker = this->scene_->add(std::make_unique<Label>(L"", font_name, }
// Every add is pending until a tick ends, so that a weapon firing mid-tick // cannot invalidate the loop walking the objects. Nothing has ticked yet // and the first frame is a real frame, so the first tick ends here. this->scene_->end_tick();
// One view, for the whole window, in screen space - the identity camera is // what a list starts with, so this one is never mentioned again. A // split-screen game clears this list and refills it every tick, one entry // per player, and nothing else about the shape changes.}The group is made in init(), which runs once for each HelloState the game
makes. The starter makes one, so this is safe. A game that makes HelloState again, as
Add a screen to your game does when it goes
back to the title, runs add_sound_group("effects") a second time and stops with
Sound group 'effects' was already added. There, make the group once, outside the state, or
ask for it by name on later runs with audio->resolve_sound_group("effects").
Saving the slider’s value, so that the game starts at the player’s last volume, is what
Save settings in your game does for another value: read it at
start and call the slider’s set_value and set_group_volume with it.
Choose a per-user folder on Windows
Section titled “Choose a per-user folder on Windows”Use the user’s LocalAppData known folder, with your game’s own subfolder. Do not write beside
the executable: an installed game may be in a read-only folder, and a relative path follows the
process’s working directory rather than the player. The Windows API supplies a Unicode path;
std::filesystem::path carries it to the standard library’s file streams.
std::filesystem::path settings_directory(){#if defined(__EMSCRIPTEN__) return "/save";#else wchar_t* raw = nullptr; if (FAILED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE, nullptr, &raw))) throw std::runtime_error("Cannot find this user's LocalAppData folder");
struct FolderDeleter { void operator()(wchar_t* value) const { CoTaskMemFree(value); } }; const std::unique_ptr<wchar_t, FolderDeleter> folder(raw); return std::filesystem::path(folder.get()) / L"MyGame";#endif}tools/save_check/settings.cpp, lines 16–32 at f525bc6
Include windows.h and shlobj.h on Windows, and link shell32.lib and ole32.lib. Replace
MyGame with your own stable name. In CMake, add those libraries to your game in its native
Windows branch, not its Emscripten branch:
target_link_libraries(MyGame PRIVATE shell32 ole32)Write JSON, then check the result
Section titled “Write JSON, then check the result”The writer makes the directory, validates the value, opens the file and enables stream
exceptions. close() completes the standard-library write and reports a buffered write failure.
Its caller catches std::exception and shows a save failure; it must not tell the player the save
succeeded merely because the settings changed in memory.
void write_settings(const std::filesystem::path& directory, int volume){ if (volume < 0 || volume > 100) throw std::invalid_argument("Volume must be from 0 to 100");
std::filesystem::create_directories(directory); std::ofstream output(directory / "settings.json", std::ios::binary | std::ios::trunc); output.exceptions(std::ios::failbit | std::ios::badbit); output << "{\"version\":1,\"volume\":" << volume << "}\n"; output.close();}tools/save_check/settings.cpp, lines 34–44 at f525bc6
Call write_settings(settings_directory(), 80) when the player applies a setting. This simple
example replaces the file in place; a progress save that must survive a crash during writing
needs your game’s recovery scheme, such as a second generation and a checked replacement. Keep
save writes out of the per-frame update path.
The standard library has no JSON parser. The engine reads JSON and writes none:
engine/assets/json.h’s read_json_file and parse_json return a document whose JsonValue
accessors check every kind and key, and that covers reading a save. Its parser, rapidjson, is
linked PRIVATE to LabradorEngine and no engine header names it, so your game cannot include
it through the engine. A game that writes JSON brings a writer of its own, from vcpkg or
vendored, on its own account. Read bytes with std::ifstream, then parse and validate them
with the reader your game chooses. Check the version, required fields, types and
ranges before applying anything. A missing settings file means defaults; malformed or unsupported
data is a reported load failure, rather than permission to silently overwrite the only copy.
The check below reads the JSON bytes in C++ and parses that tiny record in its host page;
it is a persistence example, not a general save-file parser.
Restore browser storage before starting the game
Section titled “Restore browser storage before starting the game”An ordinary Emscripten file lives in memory and disappears on reload. Mount IDBFS at /save
and call FS.syncfs(true, callback) to populate it from IndexedDB. That operation is asynchronous.
Add a run dependency before it and remove the dependency only on success, so main() cannot read
defaults and overwrite an existing save while the restore is still running.
Put this JavaScript in game/web/persist.js:
// Link with --pre-js: restore the mounted directory before C++ main reads it.if (typeof Module['preRun'] === 'function') Module['preRun'] = [Module['preRun']];Module['preRun'] ??= [];Module['preRun'].push(() => { addRunDependency('restore-save'); try { FS.mkdir('/save'); FS.mount(IDBFS, {}, '/save'); } catch (error) { abort(`Cannot mount saved settings: ${error}`); return; } FS.syncfs(true, (error) => { if (error) { abort(`Cannot restore saved settings: ${error}`); return; } removeRunDependency('restore-save'); });});
// Call only after C++ has closed the file. Await completion before another save.Module['flushSave'] = () => new Promise((resolve, reject) => { FS.syncfs(false, (error) => error ? reject(error) : resolve());});tools/save_check/persist.js at f525bc6
This is a --pre-js file, so its FS, IDBFS, addRunDependency, removeRunDependency and
abort names are inside Emscripten’s runtime. It appends to Module.preRun; keep any existing
callbacks the game’s host page has there. Add the file and IDBFS to the browser target’s existing
link options, alongside its shell and embedded-content options:
target_link_options(MyGame PRIVATE "-lidbfs.js" "--pre-js" "${CMAKE_CURRENT_SOURCE_DIR}/web/persist.js")set_property(TARGET MyGame APPEND PROPERTY LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/web/persist.js")In a starter project, copy the file from the engine’s folder, in C:\dev\mygame:
copy external\labrador\tools\save_check\persist.js game\web\which prints 1 file(s) copied. Then, in game\CMakeLists.txt, inside if(EMSCRIPTEN), add
persist.js to the LINK_DEPENDS list after shell.html, and two lines to the end of the
target_link_options block, so that the two read:
set_property(TARGET MyGame APPEND PROPERTY LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/web/shell.html" "${CMAKE_CURRENT_SOURCE_DIR}/web/persist.js" "${CMAKE_CURRENT_SOURCE_DIR}/content/manifest.json" "${CMAKE_CURRENT_SOURCE_DIR}/content/fonts/jetbrains_mono_bold_16.spritefont" ) target_link_options(MyGame PRIVATE "SHELL:--embed-file ${CMAKE_CURRENT_SOURCE_DIR}/content@/" "SHELL:--shell-file ${CMAKE_CURRENT_SOURCE_DIR}/web/shell.html" -sENVIRONMENT=web -lidbfs.js "SHELL:--pre-js ${CMAKE_CURRENT_SOURCE_DIR}/web/persist.js" )Lines other pages added to LINK_DEPENDS, such as a sound bank’s, stay where they are. Build
wasm-debug as Build for the browser does; the page starts and plays as
before, with /save restored from the browser’s storage before the game starts. That is the
storage half. Saving to it from the game, and the page button and exported function below that
finish a save, are not yet walked through in the starter project step by step; the complete
working example is the save check under Check a real reload. With only
these two changes, a file the game writes, such as the one Space writes in
Save settings in your game, is in /save until the page reloads,
and is then gone: nothing has copied it back to the browser’s storage. That copy is
the sync below.
The browser branch of settings_directory() returns /save. A file such as
/save/settings.json then uses the same std::ofstream writer as Windows. Keep the mount path
stable across releases: IDBFS uses that path to name its database.
Finish the browser sync before saying saved
Section titled “Finish the browser sync before saying saved”Closing the C++ stream updates the mounted in-memory filesystem. To persist that change, call
Module.flushSave() from your page after the C++ write has completed, and await its promise.
It calls FS.syncfs(false, callback) to copy the mounted filesystem back to IndexedDB. For
example, a page button can call an exported game function and then flush:
async function applyVolume(volume) { if (Module._save_volume(volume) !== 0) throw new Error('Could not write settings'); await Module.flushSave(); // Only now show the player's saved acknowledgement.}save_volume is this example’s extern "C" EMSCRIPTEN_KEEPALIVE wrapper around write_settings;
it returns zero on success. It is game code, not a Labrador function. Serialize save requests:
disable Apply until this promise settles, or queue the next request. Report a rejected promise
and allow a deliberate retry. Do not rely on beforeunload to finish an asynchronous write;
save at a checkpoint while the page is still running.
Browser storage belongs to the site’s origin and browser profile. A different scheme, host or port uses different storage. Private browsing, quota limits, eviction and clearing site data can remove or refuse it. Keep failures visible and provide an export/import path if progress must remain under the player’s control.
Check a real reload
Section titled “Check a real reload”The complete example and check commands
compile the C++ writer with this exact pre-js file and run a page in headless Chrome. The check
starts with a fresh profile, writes volume 37 through C++, awaits the sync, reloads the page at
the same origin, and asserts that C++ reads {"version":1,"volume":37} back before it marks the
page ready. It uses the existing browser page runner; no engine window or renderer is needed.
Use that check for storage changes, then test your game’s own validation and recovery rules separately. Build for the browser covers the rest of the browser target; Content and the manifest covers the content the engine reads.
What was checked
Section titled “What was checked”On 31 October 2026, in a starter project made from a starter ZIP of this tree, with Visual Studio
2026’s compiler 19.51 and Emscripten 6.0.12, part 1 of Play a sound in your game and steps 1 to 5
of Copy the components into your game were done as those pages word them, then
An effects volume in the starter project as worded,
by an agent editing the files with tools rather than Notepad. The build and tests passed, and
init() above is the file’s own text. Nobody listened: the game was driven with key presses and
the peak level of Windows’ default output was read after each P. It read 0.30 with the
slider at 100, 0.15 at 50 and 0 at 0, and 0 with no key pressed; a screenshot showed the
Effects row at 50. The already added message was made by calling add_sound_group
twice, and the missing focus_ line built and passed its tests. Leaving out the
audio_resources.h include also built, as another engine header already brings it in; the step
keeps it so the file says what it uses. The starter’s persist.js copy and link options above
were built with wasm-debug, and the page runner from Build for the browser loaded the page in
Edge and quit it with no errors; a save across a reload was not made in the starter.
On 13 November 2026, in a starter project made from a starter ZIP of this tree, with Emscripten
6.0.12, an agent did steps 1 to 7 of Save settings in your game and
the persist.js copy and link options above as worded, editing the files with tools. The
wasm-debug build compiled and linked with no warnings, and a change to persist.js alone
relinked the page. Headless Chrome 157 loaded it with a fresh profile, over a local server, and
the agent moved the greeting with the arrow keys and pressed Space: Saved. showed and
/save/settings.json held the position. Reloaded straight away or a second later, the page
started with no file and the greeting in the middle, and IndexedDB held nothing. Calling
Module.flushSave() from the console after Space took about 2 ms; after a reload the file
was restored before the game started, and a screenshot showed the greeting where it was saved.
The same build with the mount line changed to FS.mount(IDBFS, { autoPersist: true }, '/save')
kept the save across a reload with no flushSave() call: Emscripten’s own copy back finished
between 1 and 48 ms after Space in three runs, each before the reload. That option is not
part of this page: it reports no completion and no error to the game. No console error or
warning appeared in any run. This is a headless Chrome check on one desktop, not a check of
storage after eviction, of private browsing or of a real phone.
A second agent then followed the section as worded in another fresh starter, after the same two
pages. Its init() was byte for byte the one above, the build and tests passed, and K K
then J five times showed Effects at 50; nobody listened. It found that pasting the
const SoundGroupHandle effects line twice does not reach the game: the build stops with
C2374 and C2086 at line 133, and the already added failure comes only from a second plain
add_sound_group("effects") call, which built and failed MyGameSmokeTests with
50% tests passed, 1 tests failed out of 2. It also saw the Effects label and bar stay white
without the focus_ line. The first starter then gave the same two errors at line 133 for the
pasted line, the same test failure for the second call, and, without the focus_ line, a
screenshot with the cursor on Colour and Effects white too; the page’s boxes now say
so. The starter’s IDBFS link options and persist.js copy built and passed the page check in
its run as well.
Documentation for Labrador v0.4.0. Built from Labrador f525bc6 of 2026-11-17.