make hotbar size and layout configurable

Add hotbar-size, hotbar-layout and inventory-layout to config/defaults.toml,
player.get_hotbar_size / player.set_hotbar_size and
hud.is_hotbar_visible / hud.set_hotbar_visible.
This commit is contained in:
ostermine 2026-10-15 15:52:22 +03:00
parent 2e2233a489
commit aa670f3c9d
16 changed files with 188 additions and 20 deletions

27
dev/tests/hotbar.lua Normal file
View file

@ -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")

View file

@ -97,6 +97,9 @@ Don't be intimidated by the following text, as a minimal pack only requires `pac
- Configuration:
- `config/` - Configuration files
- `defaults.toml` - Overrides for standard content bindings, such as the player entity, default generator, etc.
- `hotbar-size` - number of hotbar slots, 10 by default (see `player.set_hotbar_size`)
- `hotbar-layout` - layout replacing the built-in hotbar, for example `"pack:hotbar"`. The root element must be `inventory`, it is bound to the player inventory. Without `position-func` the layout is placed at the bottom center of the screen
- `inventory-layout` - player inventory layout, `"core:inventory"` by default. The root element must be `inventory`
- `bindings.toml` - Keyboard/Mouse bindings
- `user-props.toml` - User properties for content definitions
- `devtools/` - Auxiliary files for internal debugging tools

View file

@ -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()
```

View file

@ -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 inventory slots selected with the mouse wheel and number keys. Default value is `hotbar-size` from `config/defaults.toml` (10). The value is not saved with the world.
```lua
player.get_selected_block(playerid: int) -> x,y,z

View file

@ -99,6 +99,9 @@ print(file.read("пак:package.json")) -- выведет содержимое p
- Конфигурация:
- `config/` - файлы конфигурации
- `defaults.toml` - переопределения стандартных привязок к контенту, такие как сущность игрока, генератор по-умолчанию и т.д.
- `hotbar-size` - число слотов хотбара, по умолчанию 10 (см. `player.set_hotbar_size`)
- `hotbar-layout` - макет, заменяющий встроенный хотбар, например `"pack:hotbar"`. Корневой элемент - `inventory`, он привязывается к инвентарю игрока. Без `position-func` макет ставится внизу по центру экрана
- `inventory-layout` - макет инвентаря игрока, по умолчанию `"core:inventory"`. Корневой элемент - `inventory`
- `bindings.toml` - привязки к клавишам / мыши
- `user-props.toml` - пользовательские свойства определений контента
- `devtools/` - вспомогательные файлы внутренних инструментов отладки

View file

@ -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()
```

View file

@ -95,9 +95,15 @@ player.get_interaction_distance(playerid: int) -> number
-- Возвращает ID инвентаря и индекс выбранного слота
player.get_inventory(playerid: int) -> int, int
-- Устанавливает выбранный слот
-- Устанавливает выбранный слот (индекс берётся по модулю размера хотбара)
player.set_selected_slot(playerid: int, slotid: int)
-- Возвращает / устанавливает размер хотбара - число первых слотов инвентаря,
-- выбираемых колесом мыши и цифровыми клавишами. По умолчанию - `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

View file

@ -1,2 +1,4 @@
generator = "core:default"
player-entity = ""
hotbar-size = 10
inventory-layout = "core:inventory"

View file

@ -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

View file

@ -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

View file

@ -143,9 +143,11 @@ std::shared_ptr<InventoryView> 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<UiDocument>(hotbarLayout);
hotbarView =
std::dynamic_pointer_cast<InventoryView>(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,
"<container size='4000' color='#00000080' z-index='-1' visible='false'/>"
@ -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<int>(Keycode::NUM_9);
i++
) {
if (input.jpressed(static_cast<Keycode>(i))) {
player.setChosenSlot(i - static_cast<int>(Keycode::NUM_1));
int slot = i - static_cast<int>(Keycode::NUM_1);
if (slot < size && input.jpressed(static_cast<Keycode>(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<int>(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<UiDocument>("core:inventory");
auto layout = content.getDefaults()["inventory-layout"].asString(
"core:inventory"
);
auto inventoryDocument = &assets.require<UiDocument>(layout);
inventoryView = std::dynamic_pointer_cast<InventoryView>(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();

View file

@ -89,6 +89,10 @@ class Hud : public util::ObjectsKeeper {
std::shared_ptr<gui::InventoryView> contentAccess;
/// @brief Player inventory hotbar
std::shared_ptr<gui::InventoryView> 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<gui::UINode> 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;

View file

@ -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<l_set_content_access>},
{"_set_debug_cheats", wrap_hud<l_set_debug_cheats>},
{"set_allow_pause", wrap_hud<l_set_allow_pause>},
{"is_hotbar_visible", wrap_hud<l_is_hotbar_visible>},
{"set_hotbar_visible", wrap_hud<l_set_hotbar_visible>},
{"reload_script", wrap_hud<l_reload_script>},
{"is_open", wrap_hud<l_is_open>},
{nullptr, nullptr}

View file

@ -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<l_get_interaction_distance>},
{"set_interaction_distance", lua::wrap<l_set_interaction_distance>},
{"set_selected_slot", lua::wrap<l_set_selected_slot>},
{"get_hotbar_size", lua::wrap<l_get_hotbar_size>},
{"set_hotbar_size", lua::wrap<l_set_hotbar_size>},
{"get_selected_block", lua::wrap<l_get_selected_block>},
{"get_selected_entity", lua::wrap<l_get_selected_entity>},
{"set_spawnpoint", lua::wrap<l_set_spawnpoint>},

View file

@ -41,6 +41,12 @@ Player::Player(
name(name),
speed(speed),
chosenSlot(0),
hotbarSize(glm::max(
1,
static_cast<int>(
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;
}

View file

@ -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> inventory;
@ -96,6 +97,10 @@ public:
int getChosenSlot() const;
void setHotbarSize(int size);
int getHotbarSize() const;
float getSpeed() const;
bool isSuspended() const;