Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Various changes #446

Merged
merged 7 commits into from
Jan 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/en/console.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

To work with the command interpreter, use the **console** library.

When sending a command via the standard console (core:console layout):
1. the `allow-cheats` rule is checked
2. the `player`, `pos.x|y|z`, `entity.id`, `entity.selected` variables are automatically set.
3. the command handler is called - console.submit or the default one.

The default handler calls console.execute, passing the result to the console.log call.

## Commands creation

To create a console command, use the following function:
Expand Down
7 changes: 7 additions & 0 deletions doc/ru/console.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

Для работы с командным интерпретатором предоставляется библиотека **console**.

При отправке команды через стандартную консоль (макет core:console):
1. проверяется правило `allow-cheats`
2. автоматически устанавливаются переменные `player`, `pos.x|y|z`, `entity.id`, `entity.selected`.
3. вызывается обработчик команд - console.submit или по-умолчанию.

Обработчик по-умолчанию вызывает console.execute, передавая результат в вызов console.log.

## Создание команд

Для создания команды консоли используется следующая функция:
Expand Down
20 changes: 13 additions & 7 deletions res/layouts/console.xml.lua
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,12 @@ end)
function setup_variables()
local pid = hud.get_player()
local x,y,z = player.get_pos(pid)
console.set("player", pid)
console.set('pos.x', x)
console.set('pos.y', y)
console.set('pos.z', z)
local pentity = player.get_entity(pid)
if pentity ~= 0 then
if pentity > 0 then
console.set('entity.id', pentity)
end
local sentity = player.get_selected_entity(pid)
Expand Down Expand Up @@ -148,8 +149,6 @@ function submit(text)
text = text:sub(2)
end
end

setup_variables()

local name
for s in text:gmatch("%S+") do
Expand All @@ -167,12 +166,19 @@ function submit(text)
end

document.log.caret = -1
local status, result = pcall(console.execute, text)
if result then
console.log(result)
end
document.prompt.text = ""
document.prompt.focused = true

setup_variables()

if console.submit then
console.submit(text)
else
local status, result = pcall(console.execute, text)
if result then
console.log(result)
end
end
end

function set_mode(mode)
Expand Down
29 changes: 24 additions & 5 deletions src/audio/audio.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,21 @@
#include "AL/ALAudio.hpp"
#include "NoAudio.hpp"
#include "debug/Logger.hpp"
#include "util/ObjectsKeeper.hpp"

static debug::Logger logger("audio");

namespace audio {
using namespace audio;

namespace {
static speakerid_t nextId = 1;
static Backend* backend;
static std::unordered_map<speakerid_t, std::unique_ptr<Speaker>> speakers;
static std::unordered_map<speakerid_t, std::shared_ptr<Stream>> streams;
static std::vector<std::unique_ptr<Channel>> channels;
static util::ObjectsKeeper objects_keeper {};
}

using namespace audio;

Channel::Channel(std::string name) : name(std::move(name)) {
}

Expand Down Expand Up @@ -148,7 +150,8 @@ class PCMVoidSource : public PCMStream {
}
};

void audio::initialize(bool enabled) {
void audio::initialize(bool enabled, AudioSettings& settings) {
enabled = enabled && settings.enabled.get();
if (enabled) {
logger.info() << "initializing ALAudio backend";
backend = ALAudio::create().release();
Expand All @@ -160,7 +163,22 @@ void audio::initialize(bool enabled) {
logger.info() << "initializing NoAudio backend";
backend = NoAudio::create().release();
}
create_channel("master");
struct {
std::string name;
NumberSetting* setting;
} builtin_channels[] {
{"master", &settings.volumeMaster},
{"regular", &settings.volumeRegular},
{"music", &settings.volumeMusic},
{"ambient", &settings.volumeAmbient},
{"ui", &settings.volumeUI}
};
for (auto& channel : builtin_channels) {
create_channel(channel.name);
objects_keeper.keepAlive(channel.setting->observe([=](auto value) {
audio::get_channel(channel.name)->setVolume(value * value);
}, true));
}
}

std::unique_ptr<PCM> audio::load_PCM(const fs::path& file, bool headerOnly) {
Expand Down Expand Up @@ -442,4 +460,5 @@ void audio::close() {
speakers.clear();
delete backend;
backend = nullptr;
objects_keeper.clearKeepedObjects();
}
3 changes: 2 additions & 1 deletion src/audio/audio.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <vector>

#include "typedefs.hpp"
#include "settings.hpp"

namespace fs = std::filesystem;

Expand Down Expand Up @@ -357,7 +358,7 @@ namespace audio {

/// @brief Initialize audio system or use no audio mode
/// @param enabled try to initialize actual audio
void initialize(bool enabled);
void initialize(bool enabled, AudioSettings& settings);

/// @brief Load audio file info and PCM data
/// @param file audio file
Expand Down
49 changes: 25 additions & 24 deletions src/engine/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,6 @@ static debug::Logger logger("engine");

namespace fs = std::filesystem;

static void create_channel(Engine* engine, std::string name, NumberSetting& setting) {
if (name != "master") {
audio::create_channel(name);
}
engine->keepAlive(setting.observe([=](auto value) {
audio::get_channel(name)->setVolume(value*value);
}, true));
}

static std::unique_ptr<ImageData> load_icon(const fs::path& resdir) {
try {
auto file = resdir / fs::u8path("textures/misc/icon.png");
Expand All @@ -73,12 +64,23 @@ static std::unique_ptr<ImageData> load_icon(const fs::path& resdir) {
return nullptr;
}

Engine::Engine(CoreParameters coreParameters)
: params(std::move(coreParameters)),
settings(),
settingsHandler({settings}),
interpreter(std::make_unique<cmd::CommandsInterpreter>()),
network(network::Network::create(settings.network)) {
Engine::Engine() = default;

static std::unique_ptr<Engine> engine;

Engine& Engine::getInstance() {
if (!engine) {
engine = std::make_unique<Engine>();
}
return *engine;
}

void Engine::initialize(CoreParameters coreParameters) {
params = std::move(coreParameters);
settingsHandler = std::make_unique<SettingsHandler>(settings);
interpreter = std::make_unique<cmd::CommandsInterpreter>();
network = network::Network::create(settings.network);

logger.info() << "engine version: " << ENGINE_VERSION_STRING;
if (params.headless) {
logger.info() << "headless mode is enabled";
Expand Down Expand Up @@ -110,12 +112,7 @@ Engine::Engine(CoreParameters coreParameters)
menus::create_version_label(*this);
}
}
audio::initialize(settings.audio.enabled.get() && !params.headless);
create_channel(this, "master", settings.audio.volumeMaster);
create_channel(this, "regular", settings.audio.volumeRegular);
create_channel(this, "music", settings.audio.volumeMusic);
create_channel(this, "ambient", settings.audio.volumeAmbient);
create_channel(this, "ui", settings.audio.volumeUI);
audio::initialize(!params.headless, settings.audio);

bool langNotSet = settings.ui.language.get() == "auto";
if (langNotSet) {
Expand All @@ -140,7 +137,7 @@ void Engine::loadSettings() {
logger.info() << "loading settings";
std::string text = files::read_string(settings_file);
try {
toml::parse(settingsHandler, settings_file.string(), text);
toml::parse(*settingsHandler, settings_file.string(), text);
} catch (const parsing_error& err) {
logger.error() << err.errorLog();
throw;
Expand Down Expand Up @@ -222,7 +219,7 @@ void Engine::renderFrame() {

void Engine::saveSettings() {
logger.info() << "saving settings";
files::write_string(paths.getSettingsFile(), toml::stringify(settingsHandler));
files::write_string(paths.getSettingsFile(), toml::stringify(*settingsHandler));
if (!params.headless) {
logger.info() << "saving bindings";
files::write_string(paths.getControlsFile(), Events::writeBindings());
Expand Down Expand Up @@ -255,6 +252,10 @@ Engine::~Engine() {
logger.info() << "engine finished";
}

void Engine::terminate() {
engine.reset();
}

EngineController* Engine::getController() {
return controller.get();
}
Expand Down Expand Up @@ -511,7 +512,7 @@ std::shared_ptr<Screen> Engine::getScreen() {
}

SettingsHandler& Engine::getSettingsHandler() {
return settingsHandler;
return *settingsHandler;
}

network::Network& Engine::getNetwork() {
Expand Down
10 changes: 8 additions & 2 deletions src/engine/Engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ using OnWorldOpen = std::function<void(std::unique_ptr<Level>, int64_t)>;
class Engine : public util::ObjectsKeeper {
CoreParameters params;
EngineSettings settings;
SettingsHandler settingsHandler;
EnginePaths paths;

std::unique_ptr<SettingsHandler> settingsHandler;
std::unique_ptr<Assets> assets;
std::shared_ptr<Screen> screen;
std::vector<ContentPack> contentPacks;
Expand All @@ -82,9 +82,15 @@ class Engine : public util::ObjectsKeeper {
void updateHotkeys();
void loadAssets();
public:
Engine(CoreParameters coreParameters);
Engine();
~Engine();

static Engine& getInstance();

void initialize(CoreParameters coreParameters);

static void terminate();

/// @brief Start the engine
void run();

Expand Down
Loading
Loading