fix building without the Wayland backend

The backend sources live in window/wayland and were picked up by the
global source glob, so a build with VOXELENGINE_WAYLAND=OFF (and any
non-Linux build, where the option is skipped entirely) tried to compile
them and failed on the generated protocol headers.

They are now collected separately and added to the target only when the
backend is enabled.

Also restores the CRLF line endings of Engine.cpp, GUI.hpp and
input.cpp, which were rewritten with LF and made their diffs look like
whole-file rewrites.
This commit is contained in:
alexei-zebra 2026-10-09 01:20:42 +03:00
parent 3b337241f5
commit 14fa7e5fd2
No known key found for this signature in database
GPG key ID: D19D450AC3D9A80E
4 changed files with 947 additions and 942 deletions

View file

@ -4,6 +4,10 @@ file(GLOB_RECURSE headers ${CMAKE_CURRENT_SOURCE_DIR}/*.hpp)
file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
list(REMOVE_ITEM sources ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) list(REMOVE_ITEM sources ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
file(GLOB_RECURSE wayland_sources
${CMAKE_CURRENT_SOURCE_DIR}/window/wayland/*.cpp)
list(REMOVE_ITEM sources ${wayland_sources})
add_library(VoxelCoreSrc STATIC ${sources} ${headers}) add_library(VoxelCoreSrc STATIC ${sources} ${headers})
find_package(OpenGL REQUIRED) find_package(OpenGL REQUIRED)
@ -120,7 +124,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND)
# tablet is referenced by cursor-shape-v1 # tablet is referenced by cursor-shape-v1
voxel_wayland_protocol(tablet-unstable-v2.xml tablet-unstable-v2) voxel_wayland_protocol(tablet-unstable-v2.xml tablet-unstable-v2)
target_sources(VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES}) target_sources(
VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources})
target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED}) target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED})
target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1) target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1)
target_link_libraries( target_link_libraries(

View file

@ -1,481 +1,481 @@
#include "Engine.hpp" #include "Engine.hpp"
#include "WindowBar.hpp" #include "WindowBar.hpp"
#ifndef GLEW_STATIC #ifndef GLEW_STATIC
#define GLEW_STATIC #define GLEW_STATIC
#endif #endif
#include "AssetsManagement.hpp" #include "AssetsManagement.hpp"
#include "audio/audio.hpp" #include "audio/audio.hpp"
#include "coders/commons.hpp" #include "coders/commons.hpp"
#include "coders/GLSLExtension.hpp" #include "coders/GLSLExtension.hpp"
#include "coders/toml.hpp" #include "coders/toml.hpp"
#include "coders/vector_fonts.hpp" #include "coders/vector_fonts.hpp"
#include "content/ContentControl.hpp" #include "content/ContentControl.hpp"
#include "core_defs.hpp" #include "core_defs.hpp"
#include "debug/Logger.hpp" #include "debug/Logger.hpp"
#include "devtools/AppScriptsControl.hpp" #include "devtools/AppScriptsControl.hpp"
#include "devtools/DebuggingServer.hpp" #include "devtools/DebuggingServer.hpp"
#include "devtools/Editor.hpp" #include "devtools/Editor.hpp"
#include "devtools/Project.hpp" #include "devtools/Project.hpp"
#include "devtools/stdin_cmd_reader.hpp" #include "devtools/stdin_cmd_reader.hpp"
#include "EnginePaths.hpp" #include "EnginePaths.hpp"
#include "frontend/locale.hpp" #include "frontend/locale.hpp"
#include "frontend/menu.hpp" #include "frontend/menu.hpp"
#include "frontend/screens/Screen.hpp" #include "frontend/screens/Screen.hpp"
#include "graphics/core/DrawContext.hpp" #include "graphics/core/DrawContext.hpp"
#include "graphics/core/Shader.hpp" #include "graphics/core/Shader.hpp"
#include "graphics/ui/elements/Menu.hpp" #include "graphics/ui/elements/Menu.hpp"
#include "graphics/ui/GUI.hpp" #include "graphics/ui/GUI.hpp"
#include "io/io.hpp" #include "io/io.hpp"
#include "io/settings_io.hpp" #include "io/settings_io.hpp"
#include "logic/CommandsInterpreter.hpp" #include "logic/CommandsInterpreter.hpp"
#include "logic/EngineController.hpp" #include "logic/EngineController.hpp"
#include "logic/scripting/scripting_hud.hpp" #include "logic/scripting/scripting_hud.hpp"
#include "logic/scripting/scripting.hpp" #include "logic/scripting/scripting.hpp"
#include "Mainloop.hpp" #include "Mainloop.hpp"
#include "network/Network.hpp" #include "network/Network.hpp"
#include "ServerMainloop.hpp" #include "ServerMainloop.hpp"
#include "util/platform.hpp" #include "util/platform.hpp"
#include "util/stringutil.hpp" #include "util/stringutil.hpp"
#include "window/input.hpp" #include "window/input.hpp"
#include "window/Window.hpp" #include "window/Window.hpp"
#include "WindowControl.hpp" #include "WindowControl.hpp"
#include "world/Level.hpp" #include "world/Level.hpp"
#include <assert.h> #include <assert.h>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <unordered_set> #include <unordered_set>
#include <functional> #include <functional>
static debug::Logger logger("engine"); static debug::Logger logger("engine");
Engine::Engine() = default; Engine::Engine() = default;
Engine::~Engine() = default; Engine::~Engine() = default;
static std::unique_ptr<Engine> instance = nullptr; static std::unique_ptr<Engine> instance = nullptr;
Engine& Engine::getInstance() { Engine& Engine::getInstance() {
if (!instance) { if (!instance) {
instance = std::make_unique<Engine>(); instance = std::make_unique<Engine>();
} }
return *instance; return *instance;
} }
void Engine::onContentLoad() { void Engine::onContentLoad() {
editor->loadTools(); editor->loadTools();
langs::setup(langs::get_current(), paths->resPaths.collectRoots()); langs::setup(langs::get_current(), paths->resPaths.collectRoots());
if (isHeadless()) { if (isHeadless()) {
return; return;
} }
for (auto& pack : content->getAllContentPacks()) { for (auto& pack : content->getAllContentPacks()) {
auto configFolder = pack.folder / "config"; auto configFolder = pack.folder / "config";
auto bindsFile = configFolder / "bindings.toml"; auto bindsFile = configFolder / "bindings.toml";
logger.info() << "loading bindings: " << bindsFile.string(); logger.info() << "loading bindings: " << bindsFile.string();
if (io::is_regular_file(bindsFile)) { if (io::is_regular_file(bindsFile)) {
input->getBindings().read( input->getBindings().read(
toml::parse( toml::parse(
bindsFile.string(), io::read_string(bindsFile) bindsFile.string(), io::read_string(bindsFile)
), ),
BindType::BIND BindType::BIND
); );
} }
} }
loadAssets(); loadAssets();
} }
void Engine::initializeClient() { void Engine::initializeClient() {
assets = std::make_unique<AssetsManagement>(*this); assets = std::make_unique<AssetsManagement>(*this);
windowControl = std::make_unique<WindowControl>(*this); windowControl = std::make_unique<WindowControl>(*this);
auto [window, input] = windowControl->initialize(); auto [window, input] = windowControl->initialize();
this->window = std::move(window); this->window = std::move(window);
this->input = std::move(input); this->input = std::move(input);
loadControls(); loadControls();
gui = std::make_unique<gui::GUI>(*this); gui = std::make_unique<gui::GUI>(*this);
if (ENGINE_DEBUG_BUILD) { if (ENGINE_DEBUG_BUILD) {
menus::create_version_label(*gui); menus::create_version_label(*gui);
} }
keepAlive(settings.display.windowMode.observe( keepAlive(settings.display.windowMode.observe(
[this](int value) { [this](int value) {
WindowMode mode = static_cast<WindowMode>(value); WindowMode mode = static_cast<WindowMode>(value);
if (mode != this->window->getMode()) { if (mode != this->window->getMode()) {
this->window->setMode(mode); this->window->setMode(mode);
} }
}, },
true true
)); ));
keepAlive(settings.debug.doTraceShaders.observe( keepAlive(settings.debug.doTraceShaders.observe(
[](bool value) { [](bool value) {
Shader::preprocessor->setTraceOutput(value); Shader::preprocessor->setTraceOutput(value);
}, },
true true
)); ));
keepAlive(this->input->addKeyCallback(Keycode::ESCAPE, [this]() { keepAlive(this->input->addKeyCallback(Keycode::ESCAPE, [this]() {
auto& menu = *gui->getMenu(); auto& menu = *gui->getMenu();
if (menu.hasOpenPage() && menu.back()) { if (menu.hasOpenPage() && menu.back()) {
return true; return true;
} }
return false; return false;
})); }));
} }
void Engine::initialize(CoreParameters coreParameters) { void Engine::initialize(CoreParameters coreParameters) {
params = std::move(coreParameters); params = std::move(coreParameters);
settingsHandler = std::make_unique<SettingsHandler>(settings); settingsHandler = std::make_unique<SettingsHandler>(settings);
logger.info() << "engine version: " << ENGINE_VERSION_STRING; logger.info() << "engine version: " << ENGINE_VERSION_STRING;
if (params.headless) { if (params.headless) {
logger.info() << "engine runs in headless mode"; logger.info() << "engine runs in headless mode";
} }
if (params.projectFolder.empty()) { if (params.projectFolder.empty()) {
params.projectFolder = params.resFolder; params.projectFolder = params.resFolder;
} }
paths = std::make_unique<EnginePaths>(params); paths = std::make_unique<EnginePaths>(params);
loadProject(); loadProject();
paths->setupProject(*project); paths->setupProject(*project);
editor = std::make_unique<devtools::Editor>(*this); editor = std::make_unique<devtools::Editor>(*this);
cmd = std::make_unique<cmd::CommandsInterpreter>(); cmd = std::make_unique<cmd::CommandsInterpreter>();
if (project->permissions.has(Permissions::NETWORK) || if (project->permissions.has(Permissions::NETWORK) ||
!params.debugServerString.empty()) { !params.debugServerString.empty()) {
network = network::Network::create(settings.network); network = network::Network::create(settings.network);
} }
if (!params.debugServerString.empty()) { if (!params.debugServerString.empty()) {
try { try {
debuggingServer = std::make_unique<devtools::DebuggingServer>( debuggingServer = std::make_unique<devtools::DebuggingServer>(
*this, params.debugServerString *this, params.debugServerString
); );
} catch (const std::runtime_error& err) { } catch (const std::runtime_error& err) {
throw initialize_error( throw initialize_error(
"debugging server error: " + std::string(err.what()) "debugging server error: " + std::string(err.what())
); );
} }
} }
loadSettings(); loadSettings();
controller = std::make_unique<EngineController>(*this); controller = std::make_unique<EngineController>(*this);
if (!params.headless) { if (!params.headless) {
initializeClient(); initializeClient();
} }
audio::initialize( audio::initialize(
!params.headless, !params.headless,
project->permissions.has(Permissions::RECORD_AUDIO), project->permissions.has(Permissions::RECORD_AUDIO),
settings.audio settings.audio
); );
vector_fonts::initialize(); vector_fonts::initialize();
if (settings.ui.language.get() == "auto") { if (settings.ui.language.get() == "auto") {
settings.ui.language.set( settings.ui.language.set(
langs::locale_by_envlocale(platform::detect_locale()) langs::locale_by_envlocale(platform::detect_locale())
); );
} }
content = std::make_unique<ContentControl>( content = std::make_unique<ContentControl>(
*project, *paths, input.get(), [this]() { onContentLoad(); } *project, *paths, input.get(), [this]() { onContentLoad(); }
); );
scripting::initialize(*this); scripting::initialize(*this);
if (!isHeadless()) { if (!isHeadless()) {
gui->getMenu()->setPageLoader(scripting::create_page_loader()); gui->getMenu()->setPageLoader(scripting::create_page_loader());
} }
keepAlive(settings.ui.language.observe([this](auto lang) { keepAlive(settings.ui.language.observe([this](auto lang) {
langs::setup(lang, paths->resPaths.collectRoots()); langs::setup(lang, paths->resPaths.collectRoots());
}, true)); }, true));
keepAlive(settings.audio.inputDevice.observe([](auto name) { keepAlive(settings.audio.inputDevice.observe([](auto name) {
audio::set_input_device(name == "auto" ? "" : name); audio::set_input_device(name == "auto" ? "" : name);
})); }));
appScripts = std::make_unique<AppScriptsControl>(params); appScripts = std::make_unique<AppScriptsControl>(params);
if (params.stdinCommands) { if (params.stdinCommands) {
cmd::start_stdin_cmd_reader(*this); cmd::start_stdin_cmd_reader(*this);
} }
} }
void Engine::loadSettings() { void Engine::loadSettings() {
io::path settings_file = EnginePaths::SETTINGS_FILE; io::path settings_file = EnginePaths::SETTINGS_FILE;
if (io::is_regular_file(settings_file)) { if (io::is_regular_file(settings_file)) {
logger.info() << "loading settings"; logger.info() << "loading settings";
std::string text = io::read_string(settings_file); std::string text = io::read_string(settings_file);
try { try {
toml::parse(*settingsHandler, settings_file.string(), text); toml::parse(*settingsHandler, settings_file.string(), text);
} catch (const parsing_error& err) { } catch (const parsing_error& err) {
logger.error() << err.errorLog(); logger.error() << err.errorLog();
throw; throw;
} }
} }
} }
void Engine::loadControls() { void Engine::loadControls() {
io::path controls_file = EnginePaths::CONTROLS_FILE; io::path controls_file = EnginePaths::CONTROLS_FILE;
if (io::is_regular_file(controls_file)) { if (io::is_regular_file(controls_file)) {
logger.info() << "loading controls"; logger.info() << "loading controls";
std::string text = io::read_string(controls_file); std::string text = io::read_string(controls_file);
input->getBindings().read( input->getBindings().read(
toml::parse(controls_file.string(), text), BindType::BIND toml::parse(controls_file.string(), text), BindType::BIND
); );
} }
} }
void Engine::updateHotkeys() { void Engine::updateHotkeys() {
if (input->jpressed(Keycode::F2)) { if (input->jpressed(Keycode::F2)) {
windowControl->saveScreenshot(); windowControl->saveScreenshot();
} }
if (input->pressed(Keycode::LEFT_CONTROL) && input->pressed(Keycode::F3) && if (input->pressed(Keycode::LEFT_CONTROL) && input->pressed(Keycode::F3) &&
input->jpressed(Keycode::U)) { input->jpressed(Keycode::U)) {
gui->toggleDebug(); gui->toggleDebug();
} }
if (input->jpressed(Keycode::F11)) { if (input->jpressed(Keycode::F11)) {
windowControl->toggleFullscreen(); windowControl->toggleFullscreen();
} }
} }
void Engine::run() { void Engine::run() {
if (params.headless) { if (params.headless) {
ServerMainloop(*this).run(); ServerMainloop(*this).run();
} else { } else {
Mainloop(*this).run(); Mainloop(*this).run();
} }
} }
void Engine::postUpdate() { void Engine::postUpdate() {
if (network) { if (network) {
network->update(); network->update();
} }
postRunnables.run(); postRunnables.run();
scripting::process_post_runnables(); scripting::process_post_runnables();
if (debuggingServer) { if (debuggingServer) {
debuggingServer->update(); debuggingServer->update();
} }
} }
void Engine::detachDebugger() { void Engine::detachDebugger() {
debuggingServer.reset(); debuggingServer.reset();
} }
void Engine::applicationTick() { void Engine::applicationTick() {
appScripts->tick(); appScripts->tick();
} }
void Engine::updateFrontend() { void Engine::updateFrontend() {
double delta = time.getDelta(); double delta = time.getDelta();
assets->update(); assets->update();
updateHotkeys(); updateHotkeys();
audio::update(delta); audio::update(delta);
gui->act(delta, window->getSize()); gui->act(delta, window->getSize());
screen->update(delta); screen->update(delta);
gui->postAct(); gui->postAct();
} }
void Engine::nextFrame(bool waitForRefresh) { void Engine::nextFrame(bool waitForRefresh) {
windowControl->nextFrame(waitForRefresh); windowControl->nextFrame(waitForRefresh);
} }
void Engine::startPauseLoop() { void Engine::startPauseLoop() {
assert (network != nullptr); assert (network != nullptr);
bool initialCursorLocked = false; bool initialCursorLocked = false;
if (!isHeadless()) { if (!isHeadless()) {
initialCursorLocked = input->isCursorLocked(); initialCursorLocked = input->isCursorLocked();
if (initialCursorLocked) { if (initialCursorLocked) {
input->toggleCursor(); input->toggleCursor();
} }
} }
while (!isQuitSignal() && debuggingServer) { while (!isQuitSignal() && debuggingServer) {
network->update(); network->update();
if (debuggingServer->update()) { if (debuggingServer->update()) {
break; break;
} }
if (isHeadless()) { if (isHeadless()) {
platform::sleep(1.0 / params.tps * 1000); platform::sleep(1.0 / params.tps * 1000);
} else { } else {
nextFrame(false); nextFrame(false);
} }
} }
if (initialCursorLocked) { if (initialCursorLocked) {
input->toggleCursor(); input->toggleCursor();
} }
} }
void Engine::renderFrame() { void Engine::renderFrame() {
if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) { if (input->isCursorLocked() != (gui->getActiveFrame() == nullptr)) {
input->toggleCursor(); input->toggleCursor();
} }
screen->draw(time.getDelta()); screen->draw(time.getDelta());
DrawContext ctx(nullptr, *window, nullptr); DrawContext ctx(nullptr, *window, nullptr);
gui->draw(ctx, *assets->getStorage()); gui->draw(ctx, *assets->getStorage());
draw_window_bar(*this); draw_window_bar(*this);
} }
void Engine::saveSettings() { void Engine::saveSettings() {
logger.info() << "saving settings"; logger.info() << "saving settings";
io::write_string(EnginePaths::SETTINGS_FILE, toml::stringify(*settingsHandler)); io::write_string(EnginePaths::SETTINGS_FILE, toml::stringify(*settingsHandler));
if (!params.headless) { if (!params.headless) {
logger.info() << "saving bindings"; logger.info() << "saving bindings";
if (input) { if (input) {
io::write_string( io::write_string(
EnginePaths::CONTROLS_FILE, input->getBindings().write() EnginePaths::CONTROLS_FILE, input->getBindings().write()
); );
} }
} }
} }
void Engine::close() { void Engine::close() {
saveSettings(); saveSettings();
logger.info() << "shutting down"; logger.info() << "shutting down";
if (screen) { if (screen) {
screen->onEngineShutdown(); screen->onEngineShutdown();
screen.reset(); screen.reset();
} }
content.reset(); content.reset();
assets.reset(); assets.reset();
cmd.reset(); cmd.reset();
if (gui) { if (gui) {
gui.reset(); gui.reset();
logger.info() << "gui finished"; logger.info() << "gui finished";
} }
if (!isHeadless()) { if (!isHeadless()) {
vector_fonts::finalize(); vector_fonts::finalize();
} }
audio::close(); audio::close();
debuggingServer.reset(); debuggingServer.reset();
network.reset(); network.reset();
clearKeepedObjects(); clearKeepedObjects();
project.reset(); project.reset();
appScripts.reset(); appScripts.reset();
scripting::close(); scripting::close();
logger.info() << "scripting finished"; logger.info() << "scripting finished";
if (!params.headless) { if (!params.headless) {
window.reset(); window.reset();
logger.info() << "window closed"; logger.info() << "window closed";
} }
logger.info() << "engine finished"; logger.info() << "engine finished";
} }
void Engine::terminate() { void Engine::terminate() {
instance->close(); instance->close();
instance.reset(); instance.reset();
} }
EngineController* Engine::getController() { EngineController* Engine::getController() {
return controller.get(); return controller.get();
} }
void Engine::setLevelConsumer(OnWorldOpen levelConsumer) { void Engine::setLevelConsumer(OnWorldOpen levelConsumer) {
this->levelConsumer = std::move(levelConsumer); this->levelConsumer = std::move(levelConsumer);
} }
void Engine::loadAssets() { void Engine::loadAssets() {
assets->loadAssets(content->get()); assets->loadAssets(content->get());
} }
void Engine::loadProject() { void Engine::loadProject() {
io::path projectFile = "project:project.toml"; io::path projectFile = "project:project.toml";
project = std::make_unique<Project>(); project = std::make_unique<Project>();
project->path = "project:"; project->path = "project:";
project->deserialize(io::read_object(projectFile)); project->deserialize(io::read_object(projectFile));
logger.info() << "loaded project " << util::quote(project->name); logger.info() << "loaded project " << util::quote(project->name);
} }
void Engine::setScreen(std::shared_ptr<Screen> screen) { void Engine::setScreen(std::shared_ptr<Screen> screen) {
if (this->screen) { if (this->screen) {
appScripts->onScreenChange(this->screen->getName(), false); appScripts->onScreenChange(this->screen->getName(), false);
} }
// reset audio channels (stop all sources) // reset audio channels (stop all sources)
audio::reset_channel(audio::get_channel_index("regular")); audio::reset_channel(audio::get_channel_index("regular"));
audio::reset_channel(audio::get_channel_index("ambient")); audio::reset_channel(audio::get_channel_index("ambient"));
this->screen = std::move(screen); this->screen = std::move(screen);
if (this->screen) { if (this->screen) {
this->screen->onOpen(); this->screen->onOpen();
} }
if (this->screen) { if (this->screen) {
appScripts->onScreenChange(this->screen->getName(), true); appScripts->onScreenChange(this->screen->getName(), true);
window->setShouldRefresh(); window->setShouldRefresh();
} }
} }
void Engine::onWorldOpen(std::unique_ptr<Level> level, int64_t localPlayer) { void Engine::onWorldOpen(std::unique_ptr<Level> level, int64_t localPlayer) {
logger.info() << "world open"; logger.info() << "world open";
levelConsumer(std::move(level), localPlayer); levelConsumer(std::move(level), localPlayer);
} }
void Engine::onWorldClosed() { void Engine::onWorldClosed() {
logger.info() << "world closed"; logger.info() << "world closed";
levelConsumer(nullptr, -1); levelConsumer(nullptr, -1);
} }
void Engine::quit() { void Engine::quit() {
logger.info() << "quitSignal set to true"; logger.info() << "quitSignal set to true";
quitSignal = true; quitSignal = true;
if (!isHeadless()) { if (!isHeadless()) {
window->setShouldClose(true); window->setShouldClose(true);
} }
} }
bool Engine::isQuitSignal() const { bool Engine::isQuitSignal() const {
return quitSignal; return quitSignal;
} }
EngineSettings& Engine::getSettings() { EngineSettings& Engine::getSettings() {
return settings; return settings;
} }
Assets* Engine::getAssets() { Assets* Engine::getAssets() {
return assets ? assets->getStorage() : nullptr; return assets ? assets->getStorage() : nullptr;
} }
Assets& Engine::requireAssets() { Assets& Engine::requireAssets() {
if (isHeadless()) { if (isHeadless()) {
throw std::runtime_error("assets are not available in headless mode"); throw std::runtime_error("assets are not available in headless mode");
} }
return *assets->getStorage(); return *assets->getStorage();
} }
AssetsLoader& Engine::acquireBackgroundLoader() { AssetsLoader& Engine::acquireBackgroundLoader() {
if (isHeadless()) { if (isHeadless()) {
throw std::runtime_error("assets are not available in headless mode"); throw std::runtime_error("assets are not available in headless mode");
} }
return assets->acquireBackgroundLoader(); return assets->acquireBackgroundLoader();
} }
EnginePaths& Engine::getPaths() { EnginePaths& Engine::getPaths() {
return *paths; return *paths;
} }
ResPaths& Engine::getResPaths() { ResPaths& Engine::getResPaths() {
return paths->resPaths; return paths->resPaths;
} }
std::shared_ptr<Screen> Engine::getScreen() { std::shared_ptr<Screen> Engine::getScreen() {
return screen; return screen;
} }
SettingsHandler& Engine::getSettingsHandler() { SettingsHandler& Engine::getSettingsHandler() {
return *settingsHandler; return *settingsHandler;
} }
Time& Engine::getTime() { Time& Engine::getTime() {
return time; return time;
} }
const CoreParameters& Engine::getCoreParameters() const { const CoreParameters& Engine::getCoreParameters() const {
return params; return params;
} }
bool Engine::isHeadless() const { bool Engine::isHeadless() const {
return params.headless; return params.headless;
} }
ContentControl& Engine::getContentControl() { ContentControl& Engine::getContentControl() {
return *content; return *content;
} }

View file

@ -1,193 +1,193 @@
#pragma once #pragma once
#include "delegates.hpp" #include "delegates.hpp"
#include <set> #include <set>
#include <queue> #include <queue>
#include <memory> #include <memory>
#include <vector> #include <vector>
#include <string> #include <string>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <unordered_map> #include <unordered_map>
class DrawContext; class DrawContext;
class Assets; class Assets;
class Camera; class Camera;
class Batch2D; class Batch2D;
struct CursorState; struct CursorState;
class Engine; class Engine;
class Input; class Input;
class Window; class Window;
struct FontStylesScheme; struct FontStylesScheme;
namespace devtools { namespace devtools {
class Editor; class Editor;
} }
class UiDocument; class UiDocument;
/* /*
Some info about padding and margin. Some info about padding and margin.
Padding is element inner space, margin is outer Padding is element inner space, margin is outer
glm::vec4 usage: glm::vec4 usage:
x - left x - left
y - top y - top
z - right z - right
w - bottom w - bottom
Outer element Outer element
+======================================================================+ +======================================================================+
| . . . . | | . . . . |
| .padding.y . . . | | .padding.y . . . |
| padding.x . . . . padding.z | | padding.x . . . . padding.z |
|- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - |
| . . . . | | . . . . |
| . .margin.y . . | | . .margin.y . . |
| .margin.x . . margin.z. | | .margin.x . . margin.z. |
|- - - - - - + - - - - - +====================+- - - - - + - - - - - - | |- - - - - - + - - - - - +====================+- - - - - + - - - - - - |
| . | Inner element | . | | . | Inner element | . |
|- - - - - - + - - - - - +====================+- - - - - + - - - - - - | |- - - - - - + - - - - - +====================+- - - - - + - - - - - - |
| . . . . | | . . . . |
| . .margin.w . . | | . .margin.w . . |
| . . . . | | . . . . |
|- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - | |- - - - - - + - - - - - + - - - - - - - - - -+- - - - - + - - - - - - |
| . . . . | | . . . . |
| .padding.w . . . | | .padding.w . . . |
| . . . . | | . . . . |
+======================================================================+ +======================================================================+
*/ */
namespace gui { namespace gui {
class UINode; class UINode;
class Container; class Container;
class Menu; class Menu;
class Frame; class Frame;
/// @brief The main UI controller /// @brief The main UI controller
class GUI { class GUI {
Engine& engine; Engine& engine;
Input& input; Input& input;
std::unique_ptr<Batch2D> batch2D; std::unique_ptr<Batch2D> batch2D;
std::shared_ptr<Frame> container; std::shared_ptr<Frame> container;
std::shared_ptr<UINode> hover; std::shared_ptr<UINode> hover;
std::shared_ptr<UINode> pressed; std::shared_ptr<UINode> pressed;
std::shared_ptr<UINode> focus; std::shared_ptr<UINode> focus;
const UINode* focusedOnStart = nullptr; const UINode* focusedOnStart = nullptr;
std::shared_ptr<UINode> tooltip; std::shared_ptr<UINode> tooltip;
std::shared_ptr<UiDocument> rootDocument; std::shared_ptr<UiDocument> rootDocument;
std::unique_ptr<FontStylesScheme> syntaxColorScheme; std::unique_ptr<FontStylesScheme> syntaxColorScheme;
std::unordered_map<std::string, std::shared_ptr<UINode>> storage; std::unordered_map<std::string, std::shared_ptr<UINode>> storage;
std::shared_ptr<Frame> activeFrame; std::shared_ptr<Frame> activeFrame;
std::unique_ptr<Camera> uicamera; std::unique_ptr<Camera> uicamera;
std::shared_ptr<Menu> menu; std::shared_ptr<Menu> menu;
std::queue<runnable> postRunnables; std::queue<runnable> postRunnables;
std::vector<std::weak_ptr<UINode>> mouseOver; std::vector<std::weak_ptr<UINode>> mouseOver;
std::unordered_map<std::string, std::shared_ptr<Frame>> frames; std::unordered_map<std::string, std::shared_ptr<Frame>> frames;
vec2supplier cursorLocator; vec2supplier cursorLocator;
float tooltipTimer = 0.0f; float tooltipTimer = 0.0f;
float doubleClickTimer = 0.0f; float doubleClickTimer = 0.0f;
float doubleClickDelay = 0.5f; float doubleClickDelay = 0.5f;
bool doubleClicked = false; bool doubleClicked = false;
bool debug = false; bool debug = false;
void actMouse(Frame& frame, float delta, const CursorState& cursor); void actMouse(Frame& frame, float delta, const CursorState& cursor);
void actFocused(); void actFocused();
void updateTooltip(float delta); void updateTooltip(float delta);
void resetTooltip(); void resetTooltip();
public: public:
static inline std::string CORE_MAIN = "core:main"; static inline std::string CORE_MAIN = "core:main";
static constexpr int CONTEXT_MENU_ZINDEX = 999; static constexpr int CONTEXT_MENU_ZINDEX = 999;
GUI(Engine& engine); GUI(Engine& engine);
~GUI(); ~GUI();
/// @brief Get the main menu (Menu) node /// @brief Get the main menu (Menu) node
std::shared_ptr<Menu> getMenu(); std::shared_ptr<Menu> getMenu();
/// @brief Get current focused node /// @brief Get current focused node
/// @return focused node or nullptr /// @return focused node or nullptr
std::shared_ptr<UINode> getFocused() const; std::shared_ptr<UINode> getFocused() const;
/// @brief Check if all user input is caught by some element like TextBox /// @brief Check if all user input is caught by some element like TextBox
bool isFocusCaught() const; bool isFocusCaught() const;
/// @brief Main input handling and logic update method /// @brief Main input handling and logic update method
/// @param delta delta time /// @param delta delta time
/// @param viewport window size /// @param viewport window size
void act(float delta, const glm::uvec2& viewport); void act(float delta, const glm::uvec2& viewport);
/// @brief Draw all visible elements on main container /// @brief Draw all visible elements on main container
/// @param pctx parent graphics context /// @param pctx parent graphics context
/// @param assets active assets storage /// @param assets active assets storage
void draw(const DrawContext& pctx, Assets& assets); void draw(const DrawContext& pctx, Assets& assets);
Batch2D* getBatch2D() { Batch2D* getBatch2D() {
return batch2D.get(); return batch2D.get();
} }
void postAct(); void postAct();
/// @brief Add element to the main container /// @brief Add element to the main container
/// @param node UI element /// @param node UI element
void add(std::shared_ptr<UINode> node); void add(std::shared_ptr<UINode> node);
void addFrame(std::shared_ptr<Frame> frame); void addFrame(std::shared_ptr<Frame> frame);
void setActiveFrame( void setActiveFrame(
const std::string& id, vec2supplier cursorLocator = nullptr const std::string& id, vec2supplier cursorLocator = nullptr
); );
std::shared_ptr<Frame> getActiveFrame() const; std::shared_ptr<Frame> getActiveFrame() const;
std::shared_ptr<Frame> getFrame(const std::string& id); std::shared_ptr<Frame> getFrame(const std::string& id);
/// @brief Remove node from the main container /// @brief Remove node from the main container
void remove(UINode* node) noexcept; void remove(UINode* node) noexcept;
void remove(const std::shared_ptr<UINode>& node) noexcept { void remove(const std::shared_ptr<UINode>& node) noexcept {
return remove(node.get()); return remove(node.get());
} }
/// @brief Store node in the GUI nodes dictionary /// @brief Store node in the GUI nodes dictionary
/// (does not add node to the main container) /// (does not add node to the main container)
/// @param name node key /// @param name node key
/// @param node target node /// @param node target node
void store(const std::string& name, std::shared_ptr<UINode> node); void store(const std::string& name, std::shared_ptr<UINode> node);
/// @brief Get node from the GUI nodes dictionary /// @brief Get node from the GUI nodes dictionary
/// @param name node key /// @param name node key
/// @return stored node or nullptr /// @return stored node or nullptr
std::shared_ptr<UINode> get(const std::string& name) noexcept; std::shared_ptr<UINode> get(const std::string& name) noexcept;
/// @brief Remove node from the GUI nodes dictionary /// @brief Remove node from the GUI nodes dictionary
/// @param name node key /// @param name node key
void remove(const std::string& name) noexcept; void remove(const std::string& name) noexcept;
/// @brief Set node as focused /// @brief Set node as focused
/// @param node new focused node or nullptr to remove focus /// @param node new focused node or nullptr to remove focus
void setFocus(std::shared_ptr<UINode> node); void setFocus(std::shared_ptr<UINode> node);
/// @brief Get the main container /// @brief Get the main container
/// @deprecated /// @deprecated
std::shared_ptr<Container> getContainer() const; std::shared_ptr<Container> getContainer() const;
void setSyntaxColorScheme(std::unique_ptr<FontStylesScheme> scheme); void setSyntaxColorScheme(std::unique_ptr<FontStylesScheme> scheme);
FontStylesScheme* getSyntaxColorScheme() const; FontStylesScheme* getSyntaxColorScheme() const;
void onAssetsLoad(Assets* assets); void onAssetsLoad(Assets* assets);
void postRunnable(const runnable& callback); void postRunnable(const runnable& callback);
void setDoubleClickDelay(float delay); void setDoubleClickDelay(float delay);
float getDoubleClickDelay() const; float getDoubleClickDelay() const;
void toggleDebug(); void toggleDebug();
const Input& getInput() const; const Input& getInput() const;
Input& getInput(); Input& getInput();
Window& getWindow(); Window& getWindow();
devtools::Editor& getEditor(); devtools::Editor& getEditor();
Engine& getEngine(); Engine& getEngine();
}; };
} }

View file

@ -1,267 +1,267 @@
#include "input.hpp" #include "input.hpp"
#include "debug/Logger.hpp" #include "debug/Logger.hpp"
#include "util/stringutil.hpp" #include "util/stringutil.hpp"
#include "data/dv.hpp" #include "data/dv.hpp"
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
#include <cctype> #include <cctype>
#include <unordered_map> #include <unordered_map>
#ifdef _WIN32 #ifdef _WIN32
#include <windows.h> #include <windows.h>
#endif // _WIN32 #endif // _WIN32
static debug::Logger logger("input"); static debug::Logger logger("input");
static std::unordered_map<std::string, int> keycodes { static std::unordered_map<std::string, int> keycodes {
{"enter", GLFW_KEY_ENTER}, {"enter", GLFW_KEY_ENTER},
{"space", GLFW_KEY_SPACE}, {"space", GLFW_KEY_SPACE},
{"backspace", GLFW_KEY_BACKSPACE}, {"backspace", GLFW_KEY_BACKSPACE},
{"caps-lock", GLFW_KEY_CAPS_LOCK}, {"caps-lock", GLFW_KEY_CAPS_LOCK},
{"escape", GLFW_KEY_ESCAPE}, {"escape", GLFW_KEY_ESCAPE},
{"delete", GLFW_KEY_DELETE}, {"delete", GLFW_KEY_DELETE},
{"home", GLFW_KEY_HOME}, {"home", GLFW_KEY_HOME},
{"end", GLFW_KEY_END}, {"end", GLFW_KEY_END},
{"tab", GLFW_KEY_TAB}, {"tab", GLFW_KEY_TAB},
{"insert", GLFW_KEY_INSERT}, {"insert", GLFW_KEY_INSERT},
{"page-down", GLFW_KEY_PAGE_DOWN}, {"page-down", GLFW_KEY_PAGE_DOWN},
{"page-up", GLFW_KEY_PAGE_UP}, {"page-up", GLFW_KEY_PAGE_UP},
{"left-shift", GLFW_KEY_LEFT_SHIFT}, {"left-shift", GLFW_KEY_LEFT_SHIFT},
{"right-shift", GLFW_KEY_RIGHT_SHIFT}, {"right-shift", GLFW_KEY_RIGHT_SHIFT},
{"left-ctrl", GLFW_KEY_LEFT_CONTROL}, {"left-ctrl", GLFW_KEY_LEFT_CONTROL},
{"right-ctrl", GLFW_KEY_RIGHT_CONTROL}, {"right-ctrl", GLFW_KEY_RIGHT_CONTROL},
{"left-alt", GLFW_KEY_LEFT_ALT}, {"left-alt", GLFW_KEY_LEFT_ALT},
{"right-alt", GLFW_KEY_RIGHT_ALT}, {"right-alt", GLFW_KEY_RIGHT_ALT},
{"left-super", GLFW_KEY_LEFT_SUPER}, {"left-super", GLFW_KEY_LEFT_SUPER},
{"right-super", GLFW_KEY_RIGHT_SUPER}, {"right-super", GLFW_KEY_RIGHT_SUPER},
{"grave-accent", GLFW_KEY_GRAVE_ACCENT}, {"grave-accent", GLFW_KEY_GRAVE_ACCENT},
{"left", GLFW_KEY_LEFT}, {"left", GLFW_KEY_LEFT},
{"right", GLFW_KEY_RIGHT}, {"right", GLFW_KEY_RIGHT},
{"down", GLFW_KEY_DOWN}, {"down", GLFW_KEY_DOWN},
{"up", GLFW_KEY_UP}, {"up", GLFW_KEY_UP},
{"num-lock", GLFW_KEY_NUM_LOCK}, {"num-lock", GLFW_KEY_NUM_LOCK},
{"print-screen", GLFW_KEY_PRINT_SCREEN}, {"print-screen", GLFW_KEY_PRINT_SCREEN},
{"num-add", GLFW_KEY_KP_ADD}, {"num-add", GLFW_KEY_KP_ADD},
{"num-multiply", GLFW_KEY_KP_MULTIPLY}, {"num-multiply", GLFW_KEY_KP_MULTIPLY},
{"num-divide", GLFW_KEY_KP_DIVIDE}, {"num-divide", GLFW_KEY_KP_DIVIDE},
{"num-subtract", GLFW_KEY_KP_SUBTRACT}, {"num-subtract", GLFW_KEY_KP_SUBTRACT},
{"num-enter", GLFW_KEY_KP_ENTER}, {"num-enter", GLFW_KEY_KP_ENTER},
{"num-equal", GLFW_KEY_KP_EQUAL}, {"num-equal", GLFW_KEY_KP_EQUAL},
{"num-decimal", GLFW_KEY_KP_DECIMAL}, {"num-decimal", GLFW_KEY_KP_DECIMAL},
}; };
static std::unordered_map<std::string, int> mousecodes { static std::unordered_map<std::string, int> mousecodes {
{"left", GLFW_MOUSE_BUTTON_1}, {"left", GLFW_MOUSE_BUTTON_1},
{"right", GLFW_MOUSE_BUTTON_2}, {"right", GLFW_MOUSE_BUTTON_2},
{"middle", GLFW_MOUSE_BUTTON_3}, {"middle", GLFW_MOUSE_BUTTON_3},
{"side1", GLFW_MOUSE_BUTTON_4}, {"side1", GLFW_MOUSE_BUTTON_4},
{"side2", GLFW_MOUSE_BUTTON_5}, {"side2", GLFW_MOUSE_BUTTON_5},
{"side3", GLFW_MOUSE_BUTTON_6}, {"side3", GLFW_MOUSE_BUTTON_6},
{"side4", GLFW_MOUSE_BUTTON_7}, {"side4", GLFW_MOUSE_BUTTON_7},
{"side5", GLFW_MOUSE_BUTTON_8}, {"side5", GLFW_MOUSE_BUTTON_8},
}; };
static std::unordered_map<int, std::string> keynames {}; static std::unordered_map<int, std::string> keynames {};
static std::unordered_map<int, std::string> buttonsnames{}; static std::unordered_map<int, std::string> buttonsnames{};
std::string input_util::get_name(Mousecode code) { std::string input_util::get_name(Mousecode code) {
const auto found = buttonsnames.find(static_cast<int>(code)); const auto found = buttonsnames.find(static_cast<int>(code));
if (found == buttonsnames.end()) { if (found == buttonsnames.end()) {
return "unknown"; return "unknown";
} }
return found->second; return found->second;
} }
std::string input_util::get_name(Keycode code) { std::string input_util::get_name(Keycode code) {
const auto found = keynames.find(static_cast<int>(code)); const auto found = keynames.find(static_cast<int>(code));
if (found == keynames.end()) { if (found == keynames.end()) {
return "unknown"; return "unknown";
} }
return found->second; return found->second;
} }
void Binding::reset(InputType type, int code) { void Binding::reset(InputType type, int code) {
this->type = type; this->type = type;
this->code = code; this->code = code;
} }
void Binding::reset(Keycode code) { void Binding::reset(Keycode code) {
reset(InputType::KEYBOARD, static_cast<int>(code)); reset(InputType::KEYBOARD, static_cast<int>(code));
} }
void Binding::reset(Mousecode code) { void Binding::reset(Mousecode code) {
reset(InputType::MOUSE, static_cast<int>(code)); reset(InputType::MOUSE, static_cast<int>(code));
} }
void input_util::initialize() { void input_util::initialize() {
for (int i = 0; i <= 9; i++) { for (int i = 0; i <= 9; i++) {
keycodes[std::to_string(i)] = GLFW_KEY_0 + i; keycodes[std::to_string(i)] = GLFW_KEY_0 + i;
} }
for (int i = 0; i < 25; i++) { for (int i = 0; i < 25; i++) {
keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i; keycodes["f" + std::to_string(i + 1)] = GLFW_KEY_F1 + i;
} }
for (char i = 'a'; i <= 'z'; i++) { for (char i = 'a'; i <= 'z'; i++) {
keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i; keycodes[std::string({i})] = GLFW_KEY_A - 'a' + i;
} }
for (int i = 0; i <= 9; i++) { for (int i = 0; i <= 9; i++) {
keycodes["num-" + std::to_string(i)] = GLFW_KEY_KP_0 + i; keycodes["num-" + std::to_string(i)] = GLFW_KEY_KP_0 + i;
} }
for (const auto& entry : keycodes) { for (const auto& entry : keycodes) {
keynames[entry.second] = entry.first; keynames[entry.second] = entry.first;
} }
for (const auto& entry : mousecodes) { for (const auto& entry : mousecodes) {
buttonsnames[entry.second] = entry.first; buttonsnames[entry.second] = entry.first;
} }
} }
Keycode input_util::keycode_from(const std::string& name) { Keycode input_util::keycode_from(const std::string& name) {
const auto& found = keycodes.find(name); const auto& found = keycodes.find(name);
if (found == keycodes.end()) { if (found == keycodes.end()) {
return Keycode::UNKNOWN; return Keycode::UNKNOWN;
} }
return static_cast<Keycode>(found->second); return static_cast<Keycode>(found->second);
} }
Mousecode input_util::mousecode_from(const std::string& name) { Mousecode input_util::mousecode_from(const std::string& name) {
const auto& found = mousecodes.find(name); const auto& found = mousecodes.find(name);
if (found == mousecodes.end()) { if (found == mousecodes.end()) {
return Mousecode::UNKNOWN; return Mousecode::UNKNOWN;
} }
return static_cast<Mousecode>(found->second); return static_cast<Mousecode>(found->second);
} }
static const char* numpad_key_names[] { static const char* numpad_key_names[] {
"Num 0", "Num 0",
"Num 1", "Num 1",
"Num 2", "Num 2",
"Num 3", "Num 3",
"Num 4", "Num 4",
"Num 5", "Num 5",
"Num 6", "Num 6",
"Num 7", "Num 7",
"Num 8", "Num 8",
"Num 9", "Num 9",
"Num .", "Num .",
"Num /", "Num /",
"Num *", "Num *",
"Num -", "Num -",
"Num +", "Num +",
"Num Enter", "Num Enter",
"Num =", "Num =",
}; };
std::string input_util::to_string(Keycode code) { std::string input_util::to_string(Keycode code) {
int icode_repr = static_cast<int>(code); int icode_repr = static_cast<int>(code);
if (icode_repr == -1) { if (icode_repr == -1) {
return "Unknown"; return "Unknown";
} }
if (icode_repr >= GLFW_KEY_KP_0 && icode_repr <= GLFW_KEY_KP_EQUAL) { if (icode_repr >= GLFW_KEY_KP_0 && icode_repr <= GLFW_KEY_KP_EQUAL) {
return numpad_key_names[icode_repr - GLFW_KEY_KP_0]; return numpad_key_names[icode_repr - GLFW_KEY_KP_0];
} }
const auto found = keynames.find(icode_repr); const auto found = keynames.find(icode_repr);
if (found == keynames.end()) { if (found == keynames.end()) {
return "Unknown"; return "Unknown";
} }
std::string result; std::string result;
bool capitalize = true; bool capitalize = true;
for (char c : found->second) { for (char c : found->second) {
if (c == '-') { if (c == '-') {
result += ' '; result += ' ';
capitalize = true; capitalize = true;
continue; continue;
} }
result += capitalize ? static_cast<char>(std::toupper(c)) : c; result += capitalize ? static_cast<char>(std::toupper(c)) : c;
capitalize = false; capitalize = false;
} }
return result; return result;
} }
std::string input_util::to_string(Mousecode code) { std::string input_util::to_string(Mousecode code) {
switch (code) { switch (code) {
case Mousecode::BUTTON_1: case Mousecode::BUTTON_1:
return "LMB"; return "LMB";
case Mousecode::BUTTON_2: case Mousecode::BUTTON_2:
return "RMB"; return "RMB";
case Mousecode::BUTTON_3: case Mousecode::BUTTON_3:
return "MMB"; return "MMB";
case Mousecode::BUTTON_4: case Mousecode::BUTTON_4:
case Mousecode::BUTTON_5: case Mousecode::BUTTON_5:
case Mousecode::BUTTON_6: case Mousecode::BUTTON_6:
case Mousecode::BUTTON_7: case Mousecode::BUTTON_7:
case Mousecode::BUTTON_8: case Mousecode::BUTTON_8:
return "XButton " + std::to_string(static_cast<int>(code) - return "XButton " + std::to_string(static_cast<int>(code) -
static_cast<int>(Mousecode::BUTTON_3)); static_cast<int>(Mousecode::BUTTON_3));
default: default:
return "unknown button"; return "unknown button";
} }
} }
const Binding& Bindings::require(const std::string& name) const { const Binding& Bindings::require(const std::string& name) const {
if (const auto found = get(name)) { if (const auto found = get(name)) {
return *found; return *found;
} }
throw std::runtime_error("binding '" + name + "' does not exist"); throw std::runtime_error("binding '" + name + "' does not exist");
} }
Binding& Bindings::require(const std::string& name) { Binding& Bindings::require(const std::string& name) {
if (const auto found = get(name)) { if (const auto found = get(name)) {
return *found; return *found;
} }
throw std::runtime_error("binding '" + name + "' does not exist"); throw std::runtime_error("binding '" + name + "' does not exist");
} }
void Bindings::read(const dv::value& map, BindType bindType) { void Bindings::read(const dv::value& map, BindType bindType) {
for (auto& [sectionName, section] : map.asObject()) { for (auto& [sectionName, section] : map.asObject()) {
for (auto& [name, value] : section.asObject()) { for (auto& [name, value] : section.asObject()) {
auto key = sectionName + "." + name; auto key = sectionName + "." + name;
auto [prefix, codename] = util::split_at(value.asString(), ':'); auto [prefix, codename] = util::split_at(value.asString(), ':');
InputType type; InputType type;
int code; int code;
if (prefix == "key") { if (prefix == "key") {
type = InputType::KEYBOARD; type = InputType::KEYBOARD;
code = static_cast<int>(input_util::keycode_from(codename)); code = static_cast<int>(input_util::keycode_from(codename));
} else if (prefix == "mouse") { } else if (prefix == "mouse") {
type = InputType::MOUSE; type = InputType::MOUSE;
code = static_cast<int>(input_util::mousecode_from(codename)); code = static_cast<int>(input_util::mousecode_from(codename));
} else { } else {
logger.error() logger.error()
<< "unknown input type: " << prefix << " (binding " << "unknown input type: " << prefix << " (binding "
<< util::quote(key) << ")"; << util::quote(key) << ")";
continue; continue;
} }
if (bindType == BindType::BIND) { if (bindType == BindType::BIND) {
bind(key, type, code); bind(key, type, code);
} else if (bindType == BindType::REBIND) { } else if (bindType == BindType::REBIND) {
rebind(key, type, code); rebind(key, type, code);
} }
} }
} }
} }
#include "coders/toml.hpp" #include "coders/toml.hpp"
std::string Bindings::write() const { std::string Bindings::write() const {
auto obj = dv::object(); auto obj = dv::object();
for (auto& entry : bindings) { for (auto& entry : bindings) {
const auto& binding = entry.second; const auto& binding = entry.second;
std::string value; std::string value;
switch (binding.type) { switch (binding.type) {
case InputType::KEYBOARD: case InputType::KEYBOARD:
value = value =
"key:" + "key:" +
input_util::get_name(static_cast<Keycode>(binding.code)); input_util::get_name(static_cast<Keycode>(binding.code));
break; break;
case InputType::MOUSE: case InputType::MOUSE:
value = value =
"mouse:" + "mouse:" +
input_util::get_name(static_cast<Mousecode>(binding.code)); input_util::get_name(static_cast<Mousecode>(binding.code));
break; break;
default: default:
throw std::runtime_error("unsupported control type"); throw std::runtime_error("unsupported control type");
} }
obj[entry.first] = std::move(value); obj[entry.first] = std::move(value);
} }
return toml::stringify(obj); return toml::stringify(obj);
} }