On this page
  1. Run it
  2. The code

Settings

Checkbox, slider, dropdown, text input — and the focus/keyboard/gamepad navigation you get without writing any. The state model, which is "your variable, by reference" and nothing else; the variable lives in include/settings.h. The two volume sliders are the rmp::audio buses, and the settings are kept with rmp::save -- read with every field defaulting to the struct, written on Apply with a "Saved" from notify(), and a damaged file said as such.

Settings, as it starts

Run it

From a clone of the framework:

rmp example 04_settings

The code

Every file of examples/ui/04_settings, as it is at the commit this site documents (on GitHub).

src/main.cpp 274 lines
// ---------------------------------------------------------------------------
// examples/ui/04_settings/src/main.cpp
//
// A settings screen: checkbox, slider, dropdown, text input — and the thing
// that makes all four playable on a TV with a controller, which is focus.
//
// THE STATE MODEL, because it is the part that surprises people coming from a
// retained-mode toolkit: every control takes YOUR variable, by reference, and
// writes to it. There is no widget object holding a copy, nothing to
// synchronise, no setter to remember. What is on screen is what is in your
// struct, because it was read this frame. Delete this file and your settings
// still exist; they were never ours.
//
// Each one returns true on the frame it changed, so "apply when something
// changes" reads exactly like that:
//
//     if (rmp::ui::checkbox("Fullscreen", cfg.fullscreen)) apply(cfg);
//
// And they are kept: load() reads them through rmp::save when the screen
// opens, store() writes them on Apply, and rmp::ui::notify() says so. The
// Settings struct stays plain data; the Value is only the shape it has on
// disk.
//
// Run it: `rmp example 04_settings`.
// ---------------------------------------------------------------------------

#include <rmp/app.h>
#include <rmp/audio.h>
#include <rmp/save.h>
#include <rmp/scene.h>
#include <rmp/ui.h>

#include "settings.h"

#include <algorithm>
#include <string>

namespace {

void apply(const Settings &s) {
    // Where you would actually act on it. Called only when something changed,
    // which is why the controls return a bool at all.
#if !defined(PLATFORM_WEB) && !defined(__EMSCRIPTEN__)
    // VSync is a window state, on and off at any time. Not on the web: the
    // browser paces the frame there and there is nothing to switch.
    if (s.vsync)
        SetWindowState(FLAG_VSYNC_HINT);
    else
        ClearWindowState(FLAG_VSYNC_HINT);
#endif
    // The two volume sliders are the audio buses. Neither call opens the
    // sound device: a game can show and apply this screen before it has made
    // a sound, and what is already playing changes at once.
    rmp::audio::set_volume(rmp::audio::Bus::MASTER, s.master);
    rmp::audio::set_volume(rmp::audio::Bus::MUSIC, s.music);
    const std::string quality(QUALITY[static_cast<std::size_t>(s.quality)]);
    TraceLog(LOG_INFO, "SETTINGS: applied (master %.2f, quality %s)",
             static_cast<double>(s.master), quality.c_str());
}

// What is on disk, over what the struct says. Every field reads with its
// current value as the default, so the first run -- no save yet -- and a save
// from an older version missing a field both simply keep the defaults. There
// is no `if` around the read for the same reason. True when the file was
// there but edited or cut short.
bool load(Settings &s) {
    rmp::Value v;
    // When the read fails, `v` stays empty and every field keeps its default
    // -- that is the whole of "the first run". Only a damaged file is worth
    // telling the player about; a missing one is simply the first time.
    const rmp::save::Result read = rmp::save::read("settings", v);
    const bool damaged = read.status == rmp::save::Status::MODIFIED ||
        read.status == rmp::save::Status::TRUNCATED;
    s.fullscreen = v["fullscreen"].as_bool(s.fullscreen);
    s.vsync = v["vsync"].as_bool(s.vsync);
    s.master = v["master"].as_float(s.master);
    s.music = v["music"].as_float(s.music);
    s.sensitivity = v["sensitivity"].as_float(s.sensitivity);
    // An index from a file is clamped before it indexes anything: a save can
    // be edited, or come from a version with a longer list.
    s.quality = std::clamp(v["quality"].as_int(s.quality), 0,
                           static_cast<int>(QUALITY.size()) - 1);
    s.language = std::clamp(v["language"].as_int(s.language), 0,
                            static_cast<int>(LANGUAGE.size()) - 1);
    s.player = std::string(v["player"].as_string(s.player));
    return damaged;
}

// True when it reached the disk.
bool store(const Settings &s) {
    rmp::Value v;
    v["fullscreen"] = s.fullscreen;
    v["vsync"] = s.vsync;
    v["master"] = s.master;
    v["music"] = s.music;
    v["sensitivity"] = s.sensitivity;
    v["quality"] = s.quality;
    v["language"] = s.language;
    v["player"] = s.player;
    return rmp::save::write("settings", v);
}

} // namespace

class SettingsScene : public rmp::Scene {
public:
    void _ready() override {
        // The controls start where the game does -- [window] vsync and [audio] in
        // the .toml -- and then whatever the player saved last time wins.
        _cfg.vsync = RMP_WINDOW_VSYNC != 0;
        _cfg.player = "Player";
        _cfg.master = rmp::audio::volume(rmp::audio::Bus::MASTER);
        _cfg.music = rmp::audio::volume(rmp::audio::Bus::MUSIC);
        _damaged = load(_cfg);
        apply(_cfg);
        _saved = _cfg;

        // The first control of a screen has the focus without asking, so Enter and
        // the A button work the moment it appears. Asking for it by name does one
        // thing more: the ring shows from the start, before the player has touched
        // a key. Name another control to start somewhere else.
        rmp::ui::focus("Fullscreen");
    }

    void _draw() override {
        rmp::ui::begin();
        rmp::ui::panel({ .box = { .width = 760 } }, [&] {
            rmp::ui::text("Settings");

            // Two columns, so that the whole screen fits the window it opens in --
            // [window] in the .toml, 800x450. In one column Apply was below the
            // bottom edge, where a mouse could not reach it. Focus still goes
            // down the first column and then the second: it follows the order the
            // controls are written in, not where they land.
            rmp::ui::row(
                { .gap = 24, .items = rmp::ui::Align::TOP_CENTER, .grow_x = true }, [&] {
                    rmp::ui::column({ .grow_x = true }, [&] {
                        // --- toggles ----------------------------------------------
                        if (rmp::ui::checkbox("Fullscreen", _cfg.fullscreen))
                            _dirty = true;
#if !defined(PLATFORM_WEB) && !defined(__EMSCRIPTEN__)
                        // Not on the web, where there is no such switch at all. That
                        // is not the same as the Subtitles box below: a control that
                        // is unavailable RIGHT NOW is disabled, one that cannot exist
                        // here is not shown.
                        if (rmp::ui::checkbox("VSync", _cfg.vsync)) _dirty = true;
#endif

                        // A control that is not available right now is disabled, not
                        // missing. A menu whose items appear and disappear is a menu
                        // nobody can learn.
                        rmp::ui::checkbox("Subtitles", _cfg.subtitles,
                                          { .enabled = false });

                        // --- sliders ----------------------------------------------
                        // Continuous: drag it anywhere, or hold left/right on a
                        // controller.
                        if (rmp::ui::slider("Master volume", _cfg.master, 0.0f, 1.0f))
                            _dirty = true;
                        if (rmp::ui::slider("Music", _cfg.music, 0.0f, 1.0f))
                            _dirty = true;

                        // step snaps to multiples, which is what you want for a value
                        // the player will want to describe to someone else ("I play on
                        // 40").
                        if (rmp::ui::slider("Sensitivity", _cfg.sensitivity, 0.0f, 1.0f,
                                            { .step = 0.05f }))
                            _dirty = true;
                    });

                    rmp::ui::column({ .grow_x = true }, [&] {
                        // --- pick one of a list -----------------------------------
                        // The dropdown owns nothing but the open/closed flag, and that
                        // is ours, not yours: the int is an index into the list you
                        // passed.
                        if (rmp::ui::dropdown("Quality", _cfg.quality, QUALITY))
                            _dirty = true;
                        if (rmp::ui::dropdown("Language", _cfg.language, LANGUAGE))
                            _dirty = true;

                        // --- typing -----------------------------------------------
                        // Edits your std::string, up to 20 characters as the player
                        // counts them.
                        if (rmp::ui::text_input(
                                "Name", _cfg.player,
                                { .placeholder = "your name", .max_length = 20 })) {
                            _dirty = true;
                        }

                        // --- actions ----------------------------------------------
                        rmp::ui::row({ .grow_x = true }, [&] {
                            if (rmp::ui::button("Revert", { .enabled = _dirty })) {
                                _cfg = _saved;
                                _dirty = false;
                            }
                            rmp::ui::spacer();
                            if (rmp::ui::button("Apply",
                                                { .style = rmp::ui::Variant::PRIMARY,
                                                  .enabled = _dirty })) {
                                apply(_cfg);
                                // A word at the bottom of the screen, gone by
                                // itself in three seconds: nothing to close, and
                                // nothing in this layout moves to make room.
                                if (store(_cfg)) {
                                    _saved = _cfg;
                                    _dirty = false;
                                    rmp::ui::notify("Saved");
                                } else {
                                    // Still unsaved, so Apply stays lit: try again.
                                    rmp::ui::notify(
                                        "Not _saved: the disk refused it",
                                        { .color = rmp::ui::ColorRole::DANGER });
                                }
                            }
                        });

                        if (_dirty) {
                            rmp::ui::text(
                                "unsaved changes",
                                { .color = rmp::ui::ColorRole::DANGER, .size = 14 });
                        }
                        if (_damaged) {
                            rmp::ui::text(
                                "the _saved settings were _damaged; these are the "
                                "defaults",
                                { .color = rmp::ui::ColorRole::MUTED, .size = 14 });
                        }
                    });
                });
        });
        rmp::ui::end();
    }

private:
    Settings _cfg;
    Settings _saved; // what was on disk, to know if anything changed
    bool _dirty = false;
    bool _damaged = false; // the saved settings were edited or cut short
};

RMP_GAME(SettingsScene);

// ---------------------------------------------------------------------------
// Focus, keyboard and gamepad — which you did not have to write
// ---------------------------------------------------------------------------
//
// Everything above is already navigable. Nothing in this file asked for it:
//
//   Tab / Down / d-pad down / left stick    next control
//   Shift+Tab / Up / d-pad up               previous
//   Enter / Space / gamepad bottom button   activate; start typing in a field
//   Enter / Escape / gamepad B              stop typing (the focus stays)
//   Left / Right / d-pad / stick            move a slider
//   Up / Down in an open dropdown           walk its items; Enter picks one,
//                                           Escape closes it unchanged
//
// The focused control draws the theme's focus ring. That colour is in the
// Theme rather than in each widget for a reason: a controller build where one
// widget forgot to draw it is a controller build that gets stuck.
//
//   rmp::ui::focus("Fullscreen")   start somewhere else than the first control
//   rmp::ui::focused()             what has it
//   rmp::ui::set_navigation_enabled(false)   if your game drives focus itself
//
// WHO GETS THE INPUT. The UI reads the pointer and the keyboard itself, so the
// game has to be told to keep its hands off:
//
//     if (!rmp::ui::wants_pointer()  && IsMouseButtonPressed(0)) shoot();
//     if (!rmp::ui::wants_keyboard() && IsKeyDown(KEY_W))        walk();
//
// Without the second one, typing "Wolf" into the name field above walks the
// player across the level. wants_keyboard() is true only while a text field
// has the keyboard: from a click on it or the focus arriving on it, until
// Enter, Escape, a click elsewhere or the focus moving on.
include/settings.h 27 lines
#pragma once
// Plain data. This is the whole model, and it is the point of the example: the
// controls take a field of this, by reference, and write to it. Delete the UI
// and your settings still exist; they were never ours.

#include <array>
#include <string>
#include <string_view>

struct Settings {
    bool fullscreen = false;
    bool vsync = true;
    bool subtitles = false;
    float master = 0.8f;
    float music = 0.5f;
    float sensitivity = 0.35f;
    int quality = 1;
    int language = 0;
    std::string player; // "Player" until the player says otherwise: see _ready()
};

// What the two dropdowns offer: a std::array the dropdown takes as a span, so
// nobody has to tell it how long the list is.
inline constexpr std::array<std::string_view, 4> QUALITY{ "Low", "Medium", "High",
                                                          "Ultra" };
inline constexpr std::array<std::string_view, 3> LANGUAGE{ "English", "Espanol",
                                                           "Francais" };