Add M9.8d rebindable engineering controls

SDL-free action/HID-key bindings with conflict validation, a staging editor and
a versioned all-or-nothing controls file (ADR-0085). The adapter maps keys
through the bindings, releases and drains on rebinding, and captures the chosen
key ahead of the toolkit and world. The client adds a Controls panel, key hints,
startup loading with a bounded rejection notice, and --controls/--show-controls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-02 11:30:17 -04:00
co-authored by Claude Opus 5.5
parent bb8c2fc359
commit 5cf8709912
23 changed files with 1292 additions and 45 deletions
+369
View File
@@ -0,0 +1,369 @@
#include "evo/client/bindings.hpp"
#include <algorithm>
#include <fstream>
#include <system_error>
#include <vector>
namespace evo::client {
namespace {
// HID keyboard usages named by their US-layout position. Usages are positional, so
// "W" is the key in that position whatever a layout prints on it. Modifiers, locks,
// system and media keys are deliberately absent (OS shortcuts, toggled state).
struct NamedKey {
KeyCode code;
std::string_view name;
};
constexpr auto keys = std::to_array<NamedKey>({
{4, "A"},
{5, "B"},
{6, "C"},
{7, "D"},
{8, "E"},
{9, "F"},
{10, "G"},
{11, "H"},
{12, "I"},
{13, "J"},
{14, "K"},
{15, "L"},
{16, "M"},
{17, "N"},
{18, "O"},
{19, "P"},
{20, "Q"},
{21, "R"},
{22, "S"},
{23, "T"},
{24, "U"},
{25, "V"},
{26, "W"},
{27, "X"},
{28, "Y"},
{29, "Z"},
{30, "1"},
{31, "2"},
{32, "3"},
{33, "4"},
{34, "5"},
{35, "6"},
{36, "7"},
{37, "8"},
{38, "9"},
{39, "0"},
{40, "Enter"},
{41, "Escape"},
{42, "Backspace"},
{43, "Tab"},
{44, "Space"},
{45, "Minus"},
{46, "Equals"},
{47, "LeftBracket"},
{48, "RightBracket"},
{49, "Backslash"},
{51, "Semicolon"},
{52, "Apostrophe"},
{53, "Grave"},
{54, "Comma"},
{55, "Period"},
{56, "Slash"},
{58, "F1"},
{59, "F2"},
{60, "F3"},
{61, "F4"},
{62, "F5"},
{63, "F6"},
{64, "F7"},
{65, "F8"},
{66, "F9"},
{67, "F10"},
{68, "F11"},
{69, "F12"},
{73, "Insert"},
{74, "Home"},
{75, "PageUp"},
{76, "Delete"},
{77, "End"},
{78, "PageDown"},
{79, "Right"},
{80, "Left"},
{81, "Down"},
{82, "Up"},
{84, "KeypadDivide"},
{85, "KeypadMultiply"},
{86, "KeypadMinus"},
{87, "KeypadPlus"},
{88, "KeypadEnter"},
{89, "Keypad1"},
{90, "Keypad2"},
{91, "Keypad3"},
{92, "Keypad4"},
{93, "Keypad5"},
{94, "Keypad6"},
{95, "Keypad7"},
{96, "Keypad8"},
{97, "Keypad9"},
{98, "Keypad0"},
{99, "KeypadPeriod"},
{100, "NonUsBackslash"},
{50, "NonUsHash"},
});
static_assert(keys.size() == 92);
struct NamedAction {
std::string_view id, name;
};
constexpr std::array<NamedAction, action_count> actions{{
{"move_left", "Move left"},
{"move_right", "Move right"},
{"move_up", "Move up"},
{"move_down", "Move down"},
{"pan_left", "Pan left"},
{"pan_right", "Pan right"},
{"pan_up", "Pan up"},
{"pan_down", "Pan down"},
{"toggle_capture", "Toggle UI capture"},
}};
constexpr KeySlots default_slots{{
{4, no_key}, // A
{7, no_key}, // D
{26, no_key}, // W
{22, no_key}, // S
{80, no_key}, // Left
{79, no_key}, // Right
{82, no_key}, // Up
{81, no_key}, // Down
{43, no_key}, // Tab
}};
constexpr std::string_view header = "evo-controls";
constexpr std::string_view blank = " \t\r"; // CRLF files are accepted.
std::string_view trim(std::string_view text) noexcept {
const auto first = text.find_first_not_of(blank);
if (first == std::string_view::npos)
return {};
const auto last = text.find_last_not_of(blank);
return text.substr(first, last - first + 1);
}
std::vector<std::string_view> tokens(std::string_view line) {
std::vector<std::string_view> out;
while (!(line = trim(line)).empty()) {
const auto end = line.find_first_of(blank);
out.push_back(line.substr(0, end));
line = end == std::string_view::npos ? std::string_view{} : line.substr(end);
}
return out;
}
BindingProblem problem(BindingError error, std::optional<Action> action = std::nullopt,
KeyCode key = no_key, std::optional<Action> other = std::nullopt) {
return {error, action, other, key};
}
std::string key_text(KeyCode key) {
const auto name = key_name(key);
return name.empty() ? std::string{"That key"} : std::string{name};
}
} // namespace
std::string_view action_id(Action action) noexcept {
return actions.at(static_cast<std::size_t>(action)).id;
}
std::string_view action_name(Action action) noexcept {
return actions.at(static_cast<std::size_t>(action)).name;
}
std::optional<Action> action_from_id(std::string_view id) noexcept {
for (std::size_t k = 0; k < actions.size(); ++k)
if (actions[k].id == id)
return static_cast<Action>(k);
return std::nullopt;
}
std::string_view key_name(KeyCode key) noexcept {
for (const auto& k : keys)
if (k.code == key)
return k.name;
return {};
}
std::optional<KeyCode> key_from_name(std::string_view name) noexcept {
for (const auto& k : keys)
if (k.name == name)
return k.code;
return std::nullopt;
}
bool bindable(KeyCode key) noexcept {
return key != escape_key && !key_name(key).empty();
}
std::string describe(const BindingProblem& p) {
const std::string action = p.action ? std::string{action_name(*p.action)} : "An action";
switch (p.error) {
case BindingError::unbindable_key:
return p.key == escape_key
? "Escape is reserved for cancelling."
: key_text(p.key) + " cannot be bound (modifier, system or unsupported key).";
case BindingError::conflict:
return key_text(p.key) + " is already bound to " +
(p.other ? std::string{action_name(*p.other)} : std::string{"another action"}) + ".";
case BindingError::missing_primary:
return action + " needs a primary key.";
case BindingError::malformed:
return "The controls file is not valid.";
case BindingError::unsupported_version:
return "The controls file is from an unsupported version.";
case BindingError::too_large:
return "The controls file is too large.";
case BindingError::unreadable:
return "The controls file could not be read.";
case BindingError::write_failed:
return "The controls could not be saved.";
}
return "Invalid controls.";
}
Bindings Bindings::defaults() noexcept {
return Bindings{default_slots};
}
std::expected<Bindings, BindingProblem> Bindings::make(const KeySlots& slots) {
for (std::size_t k = 0; k < slots.size(); ++k) {
const auto action = static_cast<Action>(k);
const auto& s = slots[k];
if (s.primary == no_key)
return std::unexpected(problem(BindingError::missing_primary, action));
for (const auto key : {s.primary, s.secondary})
if (key != no_key && !bindable(key))
return std::unexpected(problem(BindingError::unbindable_key, action, key));
if (s.secondary == s.primary)
return std::unexpected(problem(BindingError::conflict, action, s.primary, action));
for (std::size_t j = 0; j < k; ++j)
for (const auto key : {s.primary, s.secondary})
if (key != no_key && (slots[j].primary == key || slots[j].secondary == key))
return std::unexpected(
problem(BindingError::conflict, action, key, static_cast<Action>(j)));
}
return Bindings{slots};
}
std::optional<Action> Bindings::action(KeyCode key) const noexcept {
if (key == no_key)
return std::nullopt;
for (std::size_t k = 0; k < slots_.size(); ++k)
if (slots_[k].primary == key || slots_[k].secondary == key)
return static_cast<Action>(k);
return std::nullopt;
}
std::expected<void, BindingProblem> BindingEditor::assign(Action action, bool secondary,
KeyCode key) {
if (!bindable(key))
return std::unexpected(problem(BindingError::unbindable_key, action, key));
for (std::size_t k = 0; k < draft_.size(); ++k) {
const auto other = static_cast<Action>(k);
const auto& s = draft_[k];
const bool same_slot = other == action && ((secondary && s.secondary == key) ||
(!secondary && s.primary == key));
if (!same_slot && (s.primary == key || s.secondary == key))
return std::unexpected(problem(BindingError::conflict, action, key, other));
}
auto& slot = draft_[static_cast<std::size_t>(action)];
(secondary ? slot.secondary : slot.primary) = key;
return {};
}
void BindingEditor::clear_secondary(Action action) noexcept {
draft_[static_cast<std::size_t>(action)].secondary = no_key;
}
void BindingEditor::reset_defaults() noexcept {
draft_ = default_slots;
}
std::expected<Bindings, BindingProblem> BindingEditor::apply() const {
return Bindings::make(draft_);
}
std::string serialize(const Bindings& bindings) {
std::string out{header};
out += " 1\n# Aeternalis Evolution engineering client controls (key names only).\n";
for (std::size_t k = 0; k < action_count; ++k) {
const auto& s = bindings.slots()[k];
out += action_id(static_cast<Action>(k));
out += ' ';
out += key_name(s.primary);
if (s.secondary != no_key) {
out += ' ';
out += key_name(s.secondary);
}
out += '\n';
}
return out;
}
std::expected<Bindings, BindingProblem> parse_bindings(std::string_view text) {
if (text.size() > max_bindings_bytes)
return std::unexpected(problem(BindingError::too_large));
if (std::ranges::any_of(text, [](char c) {
const auto u = static_cast<unsigned char>(c);
return u >= 0x7F || (u < 0x20 && c != '\n' && c != '\r' && c != '\t');
}))
return std::unexpected(problem(BindingError::malformed));
KeySlots slots{};
std::array<bool, action_count> seen{};
bool versioned = false;
while (!text.empty()) {
const auto end = text.find('\n');
auto line = text.substr(0, end);
text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1);
if (const auto hash = line.find('#'); hash != std::string_view::npos)
line = line.substr(0, hash);
const auto t = tokens(line);
if (t.empty())
continue;
if (!versioned) {
if (t.size() != 2 || t[0] != header)
return std::unexpected(problem(BindingError::malformed));
if (t[1] != "1")
return std::unexpected(problem(BindingError::unsupported_version));
versioned = true;
continue;
}
const auto action = action_from_id(t[0]);
if (!action || t.size() < 2 || t.size() > 3 || seen[static_cast<std::size_t>(*action)])
return std::unexpected(problem(BindingError::malformed, action));
seen[static_cast<std::size_t>(*action)] = true;
auto& slot = slots[static_cast<std::size_t>(*action)];
const auto primary = key_from_name(t[1]);
const auto secondary = t.size() == 3 ? key_from_name(t[2]) : std::optional<KeyCode>{no_key};
if (!primary || !secondary)
return std::unexpected(problem(BindingError::malformed, action));
slot = {*primary, *secondary};
}
if (!versioned)
return std::unexpected(problem(BindingError::malformed));
return Bindings::make(slots); // Missing actions have no primary.
}
std::expected<Bindings, BindingProblem> load_bindings(const std::filesystem::path& file) {
std::error_code error;
const auto size = std::filesystem::file_size(file, error);
if (error || !std::filesystem::is_regular_file(file, error))
return std::unexpected(problem(BindingError::unreadable));
if (size > max_bindings_bytes)
return std::unexpected(problem(BindingError::too_large));
std::ifstream in{file, std::ios::binary};
std::string text(max_bindings_bytes + 1, '\0');
in.read(text.data(), static_cast<std::streamsize>(text.size()));
if (in.bad())
return std::unexpected(problem(BindingError::unreadable));
text.resize(static_cast<std::size_t>(in.gcount()));
return parse_bindings(text); // Re-checks size if the file grew meanwhile.
}
std::expected<void, BindingProblem> save_bindings(const Bindings& bindings,
const std::filesystem::path& file) {
auto temporary = file;
temporary += ".tmp";
const auto text = serialize(bindings);
{
std::ofstream out{temporary, std::ios::binary | std::ios::trunc};
out.write(text.data(), static_cast<std::streamsize>(text.size()));
out.flush();
if (!out)
return std::unexpected(problem(BindingError::write_failed));
}
std::error_code error;
std::filesystem::rename(temporary, file, error);
if (error) {
std::filesystem::remove(temporary, error);
return std::unexpected(problem(BindingError::write_failed));
}
return {};
}
} // namespace evo::client
+70 -23
View File
@@ -13,28 +13,13 @@
namespace evo::client {
namespace {
bool runtime_owned = false; // Process main-thread-only contract; no hidden threads.
std::optional<Key> input_key(SDL_Scancode code) {
switch (code) {
case SDL_SCANCODE_A:
return Key::left;
case SDL_SCANCODE_D:
return Key::right;
case SDL_SCANCODE_W:
return Key::up;
case SDL_SCANCODE_S:
return Key::down;
case SDL_SCANCODE_LEFT:
return Key::pan_left;
case SDL_SCANCODE_RIGHT:
return Key::pan_right;
case SDL_SCANCODE_UP:
return Key::pan_up;
case SDL_SCANCODE_DOWN:
return Key::pan_down;
default:
// World actions map onto the input contract's held-key slots in declaration order.
std::optional<Key> held_key(Action action) noexcept {
if (action == Action::toggle_capture)
return std::nullopt;
}
return static_cast<Key>(static_cast<std::uint8_t>(action));
}
static_assert(static_cast<int>(Action::pan_down) == static_cast<int>(Key::pan_down));
// Private toolkit state (ADR-0084): created after the renderer, destroyed before it.
struct Toolkit {
bool context{}, platform{}, renderer{};
@@ -104,7 +89,10 @@ struct Application::Impl {
Toolkit toolkit; // After window/renderer: destroyed first.
Overlay overlay;
InputState input;
Bindings bindings{Bindings::defaults()};
bool backlogged{false};
bool key_capture{false}; // Binding capture armed.
std::optional<KeyCode> captured_key; // Taken once by the host.
// Capture sources: an external modal/launcher, the legacy Tab toggle and the
// toolkit's own keyboard focus. World actions run only when none applies.
bool external_capture{false}, tab_capture{false}, toolkit_capture{false};
@@ -117,7 +105,7 @@ struct Application::Impl {
// that batch is discarded first. The Tab toggle is ordered within its own batch
// (CAMERA_INPUT.md): presses after it belong to the new state, no drain.
void update_capture(bool drain = true) {
const bool wanted = external_capture || tab_capture || toolkit_capture;
const bool wanted = external_capture || tab_capture || toolkit_capture || key_capture;
if (wanted == input.captured())
return;
if (!wanted && drain) {
@@ -156,6 +144,41 @@ void Application::set_ui_capture(bool captured) noexcept {
impl_->external_capture = captured;
impl_->update_capture();
}
void Application::set_bindings(const Bindings& bindings) noexcept {
auto& p = *impl_;
p.bindings = bindings;
// Held actions may belong to keys that changed meaning: release them all and drain
// whatever is already queued, exactly like a capture release.
p.backlogged = true;
p.input.admit(false);
p.press.reset();
}
const Bindings& Application::bindings() const noexcept {
return impl_->bindings;
}
void Application::begin_key_capture() noexcept {
impl_->captured_key.reset();
impl_->key_capture = true;
impl_->update_capture();
}
void Application::cancel_key_capture() noexcept {
impl_->key_capture = false;
impl_->update_capture();
}
bool Application::key_capture_active() const noexcept {
return impl_->key_capture;
}
std::optional<KeyCode> Application::take_captured_key() noexcept {
return std::exchange(impl_->captured_key, std::nullopt);
}
std::optional<std::filesystem::path> Application::settings_directory() {
char* path = SDL_GetPrefPath("Aeternalis Games", "Evolution Engineering Client");
if (path == nullptr)
return std::nullopt;
std::filesystem::path result{reinterpret_cast<const char8_t*>(path)};
SDL_free(path);
return result;
}
void Application::set_overlay(Overlay overlay) {
impl_->overlay = std::move(overlay);
}
@@ -233,9 +256,27 @@ std::expected<void, Error> Application::poll_events() {
// A press on a panel in this batch may focus a text field before the toolkit's next
// frame can report it: world key-downs after it wait for that frame (releases pass).
bool ui_pressed = false;
bool key_chosen = false; // Binding capture completed in this batch.
SDL_Event event{};
int count = 0;
for (; count < 256 && SDL_PollEvent(&event); ++count) {
// Binding capture consumes keyboard events before the toolkit and world; text
// produced by the chosen key (later in this batch) is swallowed as well.
const bool keyboard = (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP)
? event.key.windowID == id
: event.type == SDL_EVENT_TEXT_INPUT ? event.text.windowID == id
: event.type == SDL_EVENT_TEXT_EDITING ? event.edit.windowID == id
: false;
if (keyboard && (p.key_capture || (key_chosen && (event.type == SDL_EVENT_TEXT_INPUT ||
event.type == SDL_EVENT_TEXT_EDITING)))) {
if (p.key_capture && event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {
p.captured_key = static_cast<KeyCode>(event.key.scancode);
p.key_capture = false;
key_chosen = true;
p.update_capture(); // Drains the rest of this batch before world input.
}
continue;
}
// Toolkit first: widgets see every event before world input is derived.
ImGui_ImplSDL3_ProcessEvent(&event);
if (event.type == SDL_EVENT_QUIT)
@@ -274,17 +315,23 @@ std::expected<void, Error> Application::poll_events() {
if (!p.state.accepts_input()) {
p.press.reset(); // A release may never arrive for this window.
p.ui_press = false;
if (p.key_capture) { // Focus loss cancels binding capture without a key.
p.key_capture = false;
p.update_capture();
}
}
if ((event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP) &&
event.key.windowID == id) {
const bool down = event.type == SDL_EVENT_KEY_DOWN;
if (event.key.scancode == SDL_SCANCODE_TAB && down && !event.key.repeat &&
const auto action = p.bindings.action(static_cast<KeyCode>(event.key.scancode));
if (action == Action::toggle_capture && down && !event.key.repeat &&
p.state.accepts_input() && !p.backlogged && !p.external_capture &&
!p.toolkit_capture && !ui_pressed) {
p.tab_capture = !p.tab_capture;
p.update_capture(false);
}
if (const auto key = input_key(event.key.scancode); key && (!down || !ui_pressed)) {
if (const auto key = action ? held_key(*action) : std::nullopt;
key && (!down || !ui_pressed)) {
if (auto result = p.input.key(*key, down, event.key.repeat); !result)
p.input.admit(false);
}