diff --git a/dev/tests/hotbar.lua b/dev/tests/hotbar.lua new file mode 100644 index 000000000..efeb655f4 --- /dev/null +++ b/dev/tests/hotbar.lua @@ -0,0 +1,27 @@ +local util = require "core:tests_util" + +util.create_demo_world("core:default") + +local pid = player.create("Xerxes") + +local function selected_slot() + local _, slot = player.get_inventory(pid) + return slot +end + +util.check_int(10, player.get_hotbar_size(pid), "default hotbar size") + +player.set_selected_slot(pid, 12) +util.check_int(2, selected_slot(), "selected slot") + +player.set_selected_slot(pid, 8) +player.set_hotbar_size(pid, 5) +util.check_int(5, player.get_hotbar_size(pid), "hotbar size") +util.check_int(4, selected_slot(), "clamped selected slot") + +player.set_selected_slot(pid, 7) +util.check_int(2, selected_slot(), "selected slot") + +player.set_hotbar_size(pid, 0) +util.check_int(1, player.get_hotbar_size(pid), "min hotbar size") +util.check_int(0, selected_slot(), "selected slot") diff --git a/doc/en/scripting/builtins/libhud.md b/doc/en/scripting/builtins/libhud.md index 1763ff1fb..337888f51 100644 --- a/doc/en/scripting/builtins/libhud.md +++ b/doc/en/scripting/builtins/libhud.md @@ -82,6 +82,12 @@ hud.is_player_inventory_open() -> boolean -- Sets whether to allow pausing. If false, the pause menu will not pause the game. hud.set_allow_pause(flag: bool) +-- Returns true if the hotbar is not hidden with hud.set_hotbar_visible. +hud.is_hotbar_visible() -> bool + +-- Shows or hides the hotbar. Selecting a slot with the mouse wheel and number keys keeps working. +hud.set_hotbar_visible(flag: bool) + -- Function that controls the named skeleton 'hand' (see gfx.skeletons) hud.hand_controller: function() ``` diff --git a/doc/en/scripting/builtins/libplayer.md b/doc/en/scripting/builtins/libplayer.md index 1dd628b0e..8005e1713 100644 --- a/doc/en/scripting/builtins/libplayer.md +++ b/doc/en/scripting/builtins/libplayer.md @@ -142,7 +142,14 @@ Switches the player's camera. See [cameras](libcameras.md). player.set_selected_slot(playerid: int, slotid: int) ``` -Sets the selected slot index +Sets the selected slot index. The index wraps around the hotbar size. + +```lua +player.get_hotbar_size(playerid: int) -> int +player.set_hotbar_size(playerid: int, size: int) +``` + +Hotbar size getter and setter: the number of first player inventory slots that can be selected. `player.set_selected_slot` wraps the index by it, and the selected slot is moved into the range when the size decreases. Default value is `hotbar-size` from `config/defaults.toml` (10); the value is not saved with the world. On the client these slots are shown in the hotbar and selected with the mouse wheel and number keys. ```lua player.get_selected_block(playerid: int) -> x,y,z diff --git a/doc/en/xml-ui-layouts.md b/doc/en/xml-ui-layouts.md index 5a3b03bb5..4e0cafc58 100644 --- a/doc/en/xml-ui-layouts.md +++ b/doc/en/xml-ui-layouts.md @@ -218,6 +218,8 @@ Element is a container. Does not have specific attributes. > [!WARNING] > Slots not linked to an inventory will not be displayed. "Linked to an inventory" refers to the association between an inventory UI element and an inventory via an ID. This link can be explicitly established using `inventory_ui.inventory = inventory_id`. [(see ui.md)](scripting/ui.md#inventory) +A pack can replace the player inventory screen and the hotbar with its own layouts using `inventory-layout` (`"core:inventory"` by default) and `hotbar-layout` in `config/defaults.toml`. The root element of such a layout must be `inventory`, it is bound to the player inventory. The hotbar layout is placed at the bottom center of the screen unless it has `position-func`. + ## *slot* Element must be a direct sub-element of *inventory*. diff --git a/doc/ru/scripting/builtins/libhud.md b/doc/ru/scripting/builtins/libhud.md index 210c78573..ed8423bfa 100644 --- a/doc/ru/scripting/builtins/libhud.md +++ b/doc/ru/scripting/builtins/libhud.md @@ -84,6 +84,12 @@ hud.is_player_inventory_open() -> boolean -- Устанавливает разрешение на паузу. При значении false меню паузы не приостанавливает игру. hud.set_allow_pause(flag: boolean) +-- Возвращает true, если хотбар не скрыт через hud.set_hotbar_visible. +hud.is_hotbar_visible() -> boolean + +-- Показывает или скрывает хотбар. Выбор слота колесом мыши и цифровыми клавишами продолжает работать. +hud.set_hotbar_visible(flag: boolean) + -- Функция, управляющая именованным скелетом 'hand' (см. gfx.skeletons) hud.hand_controller: function() ``` diff --git a/doc/ru/scripting/builtins/libplayer.md b/doc/ru/scripting/builtins/libplayer.md index 08077e967..758c223e1 100644 --- a/doc/ru/scripting/builtins/libplayer.md +++ b/doc/ru/scripting/builtins/libplayer.md @@ -95,9 +95,17 @@ player.get_interaction_distance(playerid: int) -> number -- Возвращает ID инвентаря и индекс выбранного слота player.get_inventory(playerid: int) -> int, int --- Устанавливает выбранный слот +-- Устанавливает выбранный слот (индекс берётся по модулю размера хотбара) player.set_selected_slot(playerid: int, slotid: int) +-- Возвращает / устанавливает размер хотбара - число первых слотов инвентаря игрока, +-- доступных для выбора. player.set_selected_slot берёт индекс по модулю этого числа, +-- а при уменьшении размера выбранный слот сдвигается в допустимый диапазон. +-- По умолчанию - `hotbar-size` из `config/defaults.toml` (10), в мире не сохраняется. +-- На клиенте эти слоты показывает хотбар, они выбираются колесом мыши и цифровыми клавишами. +player.get_hotbar_size(playerid: int) -> int +player.set_hotbar_size(playerid: int, size: int) + -- Возвращает позицию выбранного блока player.get_selected_block(playerid: int) -> x,y,z diff --git a/doc/ru/xml-ui-layouts.md b/doc/ru/xml-ui-layouts.md index 9632c40b3..fa50e6c25 100644 --- a/doc/ru/xml-ui-layouts.md +++ b/doc/ru/xml-ui-layouts.md @@ -219,6 +219,8 @@ > [!WARNING] > Слоты без привязки к инвентарю не будут отображаться. Под привязкой к инвентарю понимается связь UI элемента inventory с инвентарём по id. Которая может быть явно создана через `inventory_ui.inventory = inventory_id`. [(см ui.md)](scripting/ui.md#инвентарь-inventory) +Пак может заменить экран инвентаря игрока и хотбар своими макетами через ключи `inventory-layout` (по умолчанию `"core:inventory"`) и `hotbar-layout` в `config/defaults.toml`. Корневой элемент такого макета - `inventory`, он привязывается к инвентарю игрока. Макет хотбара ставится внизу по центру экрана, если у него нет `position-func`. + ## Одиночный слот - *slot* Элемент должен находиться внутри `inventory` элемента, без посредников. diff --git a/res/config/defaults.toml b/res/config/defaults.toml index dd2bd314a..60dc656d9 100644 --- a/res/config/defaults.toml +++ b/res/config/defaults.toml @@ -1,2 +1,4 @@ generator = "core:default" player-entity = "" +hotbar-size = 10 +inventory-layout = "core:inventory" diff --git a/res/modules/inventory_utils.lua b/res/modules/inventory_utils.lua index 17089cdab..832eb4f19 100644 --- a/res/modules/inventory_utils.lua +++ b/res/modules/inventory_utils.lua @@ -2,7 +2,9 @@ local M = {} function M.share_default_func(invid, slotid) local blockinv = hud.get_block_inventory() - local playerinv = player.get_inventory(hud.get_player()) + local pid = hud.get_player() + local playerinv = player.get_inventory(pid) + local hotbar_size = player.get_hotbar_size(pid) if blockinv ~= 0 then if invid == blockinv then inventory.move(blockinv, slotid, playerinv) @@ -11,10 +13,10 @@ function M.share_default_func(invid, slotid) end elseif rules.get("allow-content-access") then inventory.set(invid, slotid, 0, 0) - elseif slotid < 10 then - inventory.move_range(invid, slotid, invid, 10) + elseif slotid < hotbar_size then + inventory.move_range(invid, slotid, invid, hotbar_size) else - inventory.move_range(invid, slotid, invid, 0, 9) + inventory.move_range(invid, slotid, invid, 0, hotbar_size - 1) end end diff --git a/res/scripts/hud.lua b/res/scripts/hud.lua index 562fe19d1..a7c43a71a 100644 --- a/res/scripts/hud.lua +++ b/res/scripts/hud.lua @@ -43,7 +43,8 @@ function on_hud_open() end local id = block.get_picking_item(block.get(x, y, z)) local inv, cur_slot = player.get_inventory(pid) - local slot = inventory.find_by_item(inv, id, 0, 9) + local hotbar_size = player.get_hotbar_size(pid) + local slot = inventory.find_by_item(inv, id, 0, hotbar_size) if slot then player.set_selected_slot(pid, slot) return @@ -51,7 +52,7 @@ function on_hud_open() if not rules.get("allow-content-access") then return end - slot = inventory.find_by_item(inv, 0, 0, 9) + slot = inventory.find_by_item(inv, 0, 0, hotbar_size) if slot then cur_slot = slot end diff --git a/src/frontend/hud.cpp b/src/frontend/hud.cpp index 6751b885c..ea097e875 100644 --- a/src/frontend/hud.cpp +++ b/src/frontend/hud.cpp @@ -143,9 +143,11 @@ std::shared_ptr Hud::createHotbar() { auto inventory = player.getInventory(); auto& content = frontend.getLevel().content; + int size = player.getHotbarSize(); + SlotLayout slotLayout(-1, glm::vec2(), false, false, nullptr, nullptr, nullptr); InventoryBuilder builder(gui); - builder.addGrid(10, 10, glm::vec2(), glm::vec4(4), true, slotLayout); + builder.addGrid(size, size, glm::vec2(), glm::vec4(4), true, slotLayout); auto view = builder.build(); view->setId("hud.hotbar"); view->setOrigin(glm::vec2(view->getSize().x/2, 0)); @@ -177,7 +179,25 @@ Hud::Hud(Engine& engine, LevelFrontend& frontend, Player& player) contentAccessPanel->setScrollable(true); contentAccessPanel->setId("hud.content-access-panel"); - hotbarView = createHotbar(); + auto hotbarLayout = + frontend.getLevel().content.getDefaults()["hotbar-layout"].asString(""); + if (hotbarLayout.empty()) { + hotbarView = createHotbar(); + } else { + hotbarDocument = &assets.require(hotbarLayout); + hotbarView = + std::dynamic_pointer_cast(hotbarDocument->getRoot()); + if (hotbarView == nullptr) { + throw std::runtime_error( + "hotbar UI root element must be 'inventory'" + ); + } + hotbarView->bind(player.getInventory(), &frontend.getLevel().content); + hotbarView->setInteractive(false); + if (hotbarView->getPositionFunc() == nullptr) { + hotbarView->setOrigin(glm::vec2(hotbarView->getSize().x / 2, 0)); + } + } darkOverlay = guiutil::create( gui, "" @@ -229,6 +249,7 @@ Hud::~Hud() { for (auto& element : elements) { onRemove(element); } + hotbarView->unbind(); gui.remove(hotbarView); gui.remove(darkOverlay); gui.remove(inventoryDropArea); @@ -263,12 +284,13 @@ void Hud::processInput(bool visible) { } void Hud::updateHotbarControl() { + int size = player.getHotbarSize(); int scroll = input.getScroll(); if (!inventoryOpen && scroll) { int slot = player.getChosenSlot(); - slot = (slot - scroll) % 10; + slot = (slot - scroll) % size; if (slot < 0) { - slot += 10; + slot += size; } player.setChosenSlot(slot); } @@ -277,11 +299,12 @@ void Hud::updateHotbarControl() { i <= static_cast(Keycode::NUM_9); i++ ) { - if (input.jpressed(static_cast(i))) { - player.setChosenSlot(i - static_cast(Keycode::NUM_1)); + int slot = i - static_cast(Keycode::NUM_1); + if (slot < size && input.jpressed(static_cast(i))) { + player.setChosenSlot(slot); } } - if (input.jpressed(Keycode::NUM_0)) { + if (size > 9 && input.jpressed(Keycode::NUM_0)) { player.setChosenSlot(9); } } @@ -375,7 +398,16 @@ void Hud::update(bool visible) { contentAccessPanel->setVisible(inventoryView != nullptr && showContentPanel); contentAccessPanel->setSize(glm::vec2(caSize.x, windowSize.y)); contentAccess->setMinSize(glm::vec2(1, windowSize.y)); - hotbarView->setVisible(visible && !(secondUI && !inventoryView)); + if (hotbarDocument == nullptr && + static_cast(hotbarView->getSlotsCount()) != + player.getHotbarSize()) { + gui.remove(hotbarView); + hotbarView = createHotbar(); + gui.add(hotbarView); + } + hotbarView->setVisible( + visible && hotbarVisible && !(secondUI && !inventoryView) + ); darkOverlay->setVisible(isMenuOpen); inventoryDropArea->setVisible(inventoryOpen); menu.setVisible(isMenuOpen); @@ -404,8 +436,16 @@ void Hud::openInventory(bool playerInventory) { if (playerInventory) { auto& content = frontend.getLevel().content; auto inventory = player.getInventory(); - auto inventoryDocument = assets.get("core:inventory"); + auto layout = content.getDefaults()["inventory-layout"].asString( + "core:inventory" + ); + auto inventoryDocument = &assets.require(layout); inventoryView = std::dynamic_pointer_cast(inventoryDocument->getRoot()); + if (inventoryView == nullptr) { + throw std::runtime_error( + "player inventory UI root element must be 'inventory'" + ); + } inventoryView->bind(inventory, &content); add(HudElement(HudElementMode::INVENTORY, inventoryDocument, inventoryView, false)); } @@ -700,7 +740,9 @@ void Hud::updateElementsPosition(const glm::uvec2& viewport) { if (exchangeSlot != nullptr) { exchangeSlot->setPos(input.getCursor().pos); } - hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65)); + if (hotbarView->getPositionFunc() == nullptr) { + hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65)); + } hotbarView->setSelected(player.getChosenSlot()); } @@ -790,6 +832,14 @@ void Hud::setAllowPause(bool flag) { allowPause = flag; } +void Hud::setHotbarVisible(bool flag) { + hotbarVisible = flag; +} + +bool Hud::isHotbarVisible() const { + return hotbarVisible; +} + bool Hud::isOpen(const std::string& layoutid) const { for (const auto& element : elements) { auto doc = element.getDocument(); diff --git a/src/frontend/hud.hpp b/src/frontend/hud.hpp index 6b5d62130..1f3b8df93 100644 --- a/src/frontend/hud.hpp +++ b/src/frontend/hud.hpp @@ -89,6 +89,10 @@ class Hud : public util::ObjectsKeeper { std::shared_ptr contentAccess; /// @brief Player inventory hotbar std::shared_ptr hotbarView; + /// @brief Hotbar layout set by 'hotbar-layout', nullptr for built-in + UiDocument* hotbarDocument = nullptr; + /// @brief Hotbar is not hidden by scripts + bool hotbarVisible = true; /// @brief Debug info and control panel (F3 key) std::shared_ptr debugPanel; /// @brief Overlay used in pause mode @@ -219,6 +223,10 @@ public: void setAllowPause(bool flag); + void setHotbarVisible(bool flag); + + bool isHotbarVisible() const; + bool isOpen(const std::string& layoutid) const; static bool showGeneratorMinimap; diff --git a/src/logic/scripting/lua/libs/libhud.cpp b/src/logic/scripting/lua/libs/libhud.cpp index a457ca6ee..eddc64401 100644 --- a/src/logic/scripting/lua/libs/libhud.cpp +++ b/src/logic/scripting/lua/libs/libhud.cpp @@ -194,6 +194,15 @@ static int l_set_allow_pause(lua::State* L) { return 0; } +static int l_is_hotbar_visible(lua::State* L) { + return lua::pushboolean(L, hud->isHotbarVisible()); +} + +static int l_set_hotbar_visible(lua::State* L) { + hud->setHotbarVisible(lua::toboolean(L, 1)); + return 0; +} + static int l_reload_script(lua::State* L) { auto packid = lua::require_string(L, 1); if (content == nullptr) { @@ -237,6 +246,8 @@ const luaL_Reg hudlib[] = { {"_set_content_access", wrap_hud}, {"_set_debug_cheats", wrap_hud}, {"set_allow_pause", wrap_hud}, + {"is_hotbar_visible", wrap_hud}, + {"set_hotbar_visible", wrap_hud}, {"reload_script", wrap_hud}, {"is_open", wrap_hud}, {nullptr, nullptr} diff --git a/src/logic/scripting/lua/libs/libplayer.cpp b/src/logic/scripting/lua/libs/libplayer.cpp index e143d368a..2ad96e7b2 100644 --- a/src/logic/scripting/lua/libs/libplayer.cpp +++ b/src/logic/scripting/lua/libs/libplayer.cpp @@ -121,7 +121,21 @@ static int l_get_inv(lua::State* L) { static int l_set_selected_slot(lua::State* L) { if (auto player = get_player(L, 1)) { - player->setChosenSlot(lua::tointeger(L, 2) % 10); + player->setChosenSlot(lua::tointeger(L, 2) % player->getHotbarSize()); + } + return 0; +} + +static int l_get_hotbar_size(lua::State* L) { + if (auto player = get_player(L, 1)) { + return lua::pushinteger(L, player->getHotbarSize()); + } + return 0; +} + +static int l_set_hotbar_size(lua::State* L) { + if (auto player = get_player(L, 1)) { + player->setHotbarSize(lua::tointeger(L, 2)); } return 0; } @@ -401,6 +415,8 @@ const luaL_Reg playerlib[] = { {"get_interaction_distance", lua::wrap}, {"set_interaction_distance", lua::wrap}, {"set_selected_slot", lua::wrap}, + {"get_hotbar_size", lua::wrap}, + {"set_hotbar_size", lua::wrap}, {"get_selected_block", lua::wrap}, {"get_selected_entity", lua::wrap}, {"set_spawnpoint", lua::wrap}, diff --git a/src/objects/Player.cpp b/src/objects/Player.cpp index 28153d635..bc40fdb86 100644 --- a/src/objects/Player.cpp +++ b/src/objects/Player.cpp @@ -41,6 +41,12 @@ Player::Player( name(name), speed(speed), chosenSlot(0), + hotbarSize(glm::max( + 1, + static_cast( + level.content.getDefaults()["hotbar-size"].asInteger(10) + ) + )), position(position), inventory(std::move(inv)), eid(eid), @@ -153,13 +159,22 @@ void Player::attemptToChooseSpawnpoint() { } void Player::setChosenSlot(int index) { - chosenSlot = index; + chosenSlot = glm::clamp(index, 0, hotbarSize - 1); } int Player::getChosenSlot() const { return chosenSlot; } +void Player::setHotbarSize(int size) { + hotbarSize = glm::max(1, size); + setChosenSlot(chosenSlot); +} + +int Player::getHotbarSize() const { + return hotbarSize; +} + float Player::getSpeed() const { return speed; } diff --git a/src/objects/Player.hpp b/src/objects/Player.hpp index 54ed70023..57e7cb4b2 100644 --- a/src/objects/Player.hpp +++ b/src/objects/Player.hpp @@ -49,6 +49,7 @@ class Player : public Serializable { float speed; int chosenSlot; + int hotbarSize; glm::vec3 position; glm::vec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")}; std::shared_ptr inventory; @@ -96,6 +97,10 @@ public: int getChosenSlot() const; + void setHotbarSize(int size); + + int getHotbarSize() const; + float getSpeed() const; bool isSuspended() const;