Merge pull request #397 from ludovic111/feat/inventory-sort
Sort buttons for the inventory and chests (extra, off by default)
This commit is contained in:
@@ -240,6 +240,16 @@ impl Creative {
|
||||
search_index,
|
||||
}
|
||||
}
|
||||
/// Where a stack comes in the creative tabs (the search tab lists them
|
||||
/// all, in tab order): the same stack's place, else its item's first.
|
||||
/// None for items the tabs don't show.
|
||||
pub fn order_of(&self, stack: &ItemStack) -> Option<usize> {
|
||||
let items = &self.search_items;
|
||||
items
|
||||
.iter()
|
||||
.position(|s| s.same_item_same_components(stack))
|
||||
.or_else(|| items.iter().position(|s| s.item == stack.item))
|
||||
}
|
||||
pub fn tab(&self) -> &Tab {
|
||||
&self.tabs[self.selected.min(self.tabs.len() - 1)]
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ use std::{collections::VecDeque, fs, path::Path};
|
||||
pub const FILE: &str = "horizon-extras.txt";
|
||||
/// The name the options screen uses while the zoom key waits for a key.
|
||||
pub const ZOOM_KEY: &str = "horizon.zoom";
|
||||
/// The same for the sort key.
|
||||
pub const SORT_KEY: &str = "horizon.sort";
|
||||
/// Zoom levels the default cycles through, and the wheel's limits.
|
||||
pub const ZOOM_LEVELS: [u8; 6] = [2, 3, 4, 6, 8, 10];
|
||||
pub const ZOOM_MIN: f32 = 1.25;
|
||||
@@ -98,6 +100,10 @@ pub struct Extras {
|
||||
pub mouse_tweaks: bool,
|
||||
/// With them, the wheel over a slot moves its items one at a time.
|
||||
pub mouse_tweaks_wheel: bool,
|
||||
/// Sort buttons on the inventory and chest-like containers.
|
||||
pub sort: bool,
|
||||
/// A vanilla key name: sorts the part under the cursor.
|
||||
pub sort_key: String,
|
||||
}
|
||||
impl Default for Extras {
|
||||
fn default() -> Self {
|
||||
@@ -122,6 +128,8 @@ impl Default for Extras {
|
||||
auto_reconnect: false,
|
||||
mouse_tweaks: false,
|
||||
mouse_tweaks_wheel: true,
|
||||
sort: false,
|
||||
sort_key: "key.keyboard.unknown".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,6 +189,8 @@ impl Extras {
|
||||
"autoReconnect" => e.auto_reconnect = flag(e.auto_reconnect),
|
||||
"mouseTweaks" => e.mouse_tweaks = flag(e.mouse_tweaks),
|
||||
"mouseTweaksWheel" => e.mouse_tweaks_wheel = flag(e.mouse_tweaks_wheel),
|
||||
"sort" => e.sort = flag(e.sort),
|
||||
"sortKey" if value.starts_with("key.") => e.sort_key = value.to_owned(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -188,7 +198,7 @@ impl Extras {
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\n",
|
||||
"zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n",
|
||||
bool_text(self.zoom),
|
||||
self.zoom_key,
|
||||
self.zoom_level,
|
||||
@@ -213,8 +223,20 @@ impl Extras {
|
||||
bool_text(self.auto_reconnect),
|
||||
bool_text(self.mouse_tweaks),
|
||||
bool_text(self.mouse_tweaks_wheel),
|
||||
bool_text(self.sort),
|
||||
self.sort_key,
|
||||
)
|
||||
}
|
||||
/// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for
|
||||
/// another name (a vanilla mapping).
|
||||
pub fn set_key(&mut self, name: &str, value: String) -> bool {
|
||||
match name {
|
||||
ZOOM_KEY => self.zoom_key = value,
|
||||
SORT_KEY => self.sort_key = value,
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Written only once something differs from the defaults, so a vanilla
|
||||
/// setup gains no file.
|
||||
pub fn save(&self, dir: &Path) {
|
||||
@@ -416,6 +438,8 @@ pub enum Item {
|
||||
AutoReconnect,
|
||||
MouseTweaks,
|
||||
MouseTweaksWheel,
|
||||
Sort,
|
||||
SortKey,
|
||||
}
|
||||
/// The Extras page: headers and items.
|
||||
pub fn rows() -> Vec<Result<Item, &'static str>> {
|
||||
@@ -445,6 +469,8 @@ pub fn rows() -> Vec<Result<Item, &'static str>> {
|
||||
Err("Inventory"),
|
||||
Ok(MouseTweaks),
|
||||
Ok(MouseTweaksWheel),
|
||||
Ok(Sort),
|
||||
Ok(SortKey),
|
||||
Err("Multiplayer"),
|
||||
Ok(AutoReconnect),
|
||||
]
|
||||
@@ -482,6 +508,8 @@ impl Item {
|
||||
Item::AutoReconnect => "Auto-reconnect",
|
||||
Item::MouseTweaks => "Mouse Tweaks controls",
|
||||
Item::MouseTweaksWheel => "Scroll wheel moves items",
|
||||
Item::Sort => "Sort buttons",
|
||||
Item::SortKey => "Sort key",
|
||||
Item::FpsLows => "Minimum and 1% low",
|
||||
Item::Keystrokes => "Keystrokes",
|
||||
Item::KeystrokesCps => "Clicks per second",
|
||||
@@ -514,6 +542,12 @@ impl Item {
|
||||
Item::MouseTweaksWheel => {
|
||||
"Down sends one item of the slot to the other side, up brings one back."
|
||||
}
|
||||
Item::Sort => {
|
||||
"Sorts the inventory, chests, barrels, ender chests and shulker boxes in creative tab order, merging stacks."
|
||||
}
|
||||
Item::SortKey => {
|
||||
"Sorts the part under the cursor. Click, then press a key; Escape unbinds it."
|
||||
}
|
||||
Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.",
|
||||
Item::KeystrokesCps => "Clicks in the last second under each mouse button.",
|
||||
}
|
||||
@@ -524,7 +558,7 @@ impl Item {
|
||||
match self {
|
||||
Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None),
|
||||
Item::Minimap => Some(Cost::Low),
|
||||
Item::AutoReconnect | Item::MouseTweaks => Some(Cost::None),
|
||||
Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -543,6 +577,7 @@ impl Item {
|
||||
Item::AutoReconnect => e.auto_reconnect,
|
||||
Item::MouseTweaks => e.mouse_tweaks,
|
||||
Item::MouseTweaksWheel => e.mouse_tweaks_wheel,
|
||||
Item::Sort => e.sort,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -550,6 +585,7 @@ impl Item {
|
||||
pub fn value(self, e: &Extras) -> String {
|
||||
match self {
|
||||
Item::ZoomKey => crate::keybinds::display_name(&e.zoom_key).plain(),
|
||||
Item::SortKey => crate::keybinds::display_name(&e.sort_key).plain(),
|
||||
Item::ZoomLevel => format!("{}x", e.zoom_level),
|
||||
Item::FpsCorner => e.fps_corner.label().into(),
|
||||
Item::KeystrokesCorner => e.keystrokes_corner.label().into(),
|
||||
@@ -587,6 +623,7 @@ impl Item {
|
||||
Item::AutoReconnect => e.auto_reconnect = !e.auto_reconnect,
|
||||
Item::MouseTweaks => e.mouse_tweaks = !e.mouse_tweaks,
|
||||
Item::MouseTweaksWheel => e.mouse_tweaks_wheel = !e.mouse_tweaks_wheel,
|
||||
Item::Sort => e.sort = !e.sort,
|
||||
Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back),
|
||||
Item::MinimapSize => {
|
||||
let sizes: Vec<u8> = MINIMAP_SIZES.iter().map(|s| s.0).collect();
|
||||
@@ -594,7 +631,15 @@ impl Item {
|
||||
}
|
||||
Item::MinimapShape => e.minimap_round = !e.minimap_round,
|
||||
Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back),
|
||||
Item::ZoomKey => {}
|
||||
Item::ZoomKey | Item::SortKey => {}
|
||||
}
|
||||
}
|
||||
/// The key name the options screen waits on for a key item.
|
||||
pub fn key_name(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Item::ZoomKey => Some(ZOOM_KEY),
|
||||
Item::SortKey => Some(SORT_KEY),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -607,7 +652,7 @@ mod tests {
|
||||
fn everything_is_off_by_default_and_round_trips() {
|
||||
let d = Extras::default();
|
||||
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect);
|
||||
assert!(!d.mouse_tweaks);
|
||||
assert!(!d.mouse_tweaks && !d.sort);
|
||||
assert_eq!(Extras::parse(""), d);
|
||||
assert_eq!(Extras::parse(&d.serialize()), d);
|
||||
let mut e = d.clone();
|
||||
@@ -626,6 +671,8 @@ mod tests {
|
||||
e.auto_reconnect = true;
|
||||
e.mouse_tweaks = true;
|
||||
e.mouse_tweaks_wheel = false;
|
||||
e.sort = true;
|
||||
e.sort_key = "key.keyboard.r".into();
|
||||
assert_eq!(Extras::parse(&e.serialize()), e);
|
||||
}
|
||||
|
||||
|
||||
@@ -4269,6 +4269,7 @@ impl Game<'_> {
|
||||
self.draw_inventory_player(batch, ox, oy);
|
||||
}
|
||||
self.draw_inventory_slots(batch, ox, oy);
|
||||
self.draw_sort_buttons(batch, ox, oy);
|
||||
self.draw_recipe_book(batch);
|
||||
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
|
||||
let (sx, sy) = self.slot_position(slot);
|
||||
@@ -4784,6 +4785,9 @@ impl Game<'_> {
|
||||
fn inventory_press(&mut self, right: bool) {
|
||||
use horizon_client::container_screen::Target;
|
||||
use horizon_client::menu::Input;
|
||||
if !right && self.sort_press() {
|
||||
return;
|
||||
}
|
||||
let (slot, outside) = self.inventory_target();
|
||||
let shift = self.has_shift_down();
|
||||
let target = Target::of(slot, outside);
|
||||
@@ -8661,6 +8665,9 @@ impl Game<'_> {
|
||||
}
|
||||
/// A key press while a world is open (keyboard or control socket).
|
||||
fn key_pressed(&mut self, key: KeyCode) -> Result<()> {
|
||||
if self.sort_key_press(key) {
|
||||
return Ok(());
|
||||
}
|
||||
if self.remote.is_some() && self.remote_key(key)? {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Horizon's Mouse Tweaks-style controls (#332, `docs/extras.md`), off by
|
||||
//! default: while the extra is off every hook returns false and the screen
|
||||
//! clicks exactly as vanilla's. Each action is made of ordinary slot clicks
|
||||
//! Horizon's inventory extras (#332, `docs/extras.md`), Mouse Tweaks-style
|
||||
//! controls and sorting, both off by default: while an extra is off its
|
||||
//! hooks return false and the screen clicks exactly as vanilla's. Each action is made of ordinary slot clicks
|
||||
//! (the menu engine's, or `ContainerClick`s on a server), so it works
|
||||
//! wherever vanilla's clicks do. They run in the player inventory and the
|
||||
//! chest-like containers (chests, barrels, ender chests, shulker boxes,
|
||||
@@ -14,8 +14,24 @@
|
||||
//! - The wheel over a slot, with an empty hand: down moves one of its items
|
||||
//! to the other side (container and inventory, or hotbar and inventory),
|
||||
//! up brings one of the same item back.
|
||||
//!
|
||||
//! Sorting draws a small button by the container's title and one by the
|
||||
//! inventory's (an optional key sorts the part under the cursor); the
|
||||
//! clicks come from `inv_sort::plan`.
|
||||
use super::{Creative, Game, Screen};
|
||||
use horizon_client::{containers::BlockEntity, items::ItemStack, menu::Input};
|
||||
use horizon_client::{
|
||||
containers::BlockEntity,
|
||||
hud::{HudBatch, rgba},
|
||||
inv_sort,
|
||||
items::ItemStack,
|
||||
keybinds,
|
||||
menu::Input,
|
||||
stations::hover_name,
|
||||
};
|
||||
use winit::keyboard::KeyCode;
|
||||
|
||||
/// A sort button's side in GUI pixels.
|
||||
const SORT_BUTTON: f32 = 9.0;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Tweaks {
|
||||
@@ -272,3 +288,129 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The sort buttons of the open screen, with the extra on: their
|
||||
/// corner (from the screen's) and the slots each sorts. The container's
|
||||
/// (chest-like ones only) sits by its title, the main inventory's by
|
||||
/// the "Inventory" label's line.
|
||||
fn sort_buttons(&self) -> Vec<((f32, f32), Vec<usize>)> {
|
||||
if !self.settings.extras.sort
|
||||
|| self.screen != Screen::Inventory
|
||||
|| self.station.is_some()
|
||||
|| self.mount_active()
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let chest_like = if self.remote.is_some() {
|
||||
if !self.remote_storage_open() {
|
||||
return Vec::new();
|
||||
}
|
||||
true
|
||||
} else {
|
||||
match self.container_kind() {
|
||||
None => false,
|
||||
Some(BlockEntity::Chest(_)) => {
|
||||
self.chest_rows().is_some() || self.container_block_is_shulker()
|
||||
}
|
||||
Some(_) => return Vec::new(),
|
||||
}
|
||||
};
|
||||
let mut buttons = Vec::new();
|
||||
let container: Vec<usize> = self
|
||||
.slots()
|
||||
.into_iter()
|
||||
.filter(|s| (300..500).contains(s))
|
||||
.collect();
|
||||
if chest_like && !container.is_empty() {
|
||||
buttons.push(((160.0, 5.0), container));
|
||||
}
|
||||
buttons.push(((160.0, self.screen_height() - 95.0), (9..36).collect()));
|
||||
buttons
|
||||
}
|
||||
/// The sort buttons: a bordered square with three bars, lighter under
|
||||
/// the cursor.
|
||||
pub(super) fn draw_sort_buttons(&self, batch: &mut HudBatch, ox: f32, oy: f32) {
|
||||
let atlas = &self.res.atlas;
|
||||
for ((x, y), _) in self.sort_buttons() {
|
||||
let (x, y) = (ox + x, oy + y);
|
||||
let (cx, cy) = self.cursor;
|
||||
let hovered = cx >= x && cx < x + SORT_BUTTON && cy >= y && cy < y + SORT_BUTTON;
|
||||
let face = if hovered {
|
||||
rgba(220, 220, 220, 255)
|
||||
} else {
|
||||
rgba(160, 160, 160, 255)
|
||||
};
|
||||
batch.fill(atlas, x, y, SORT_BUTTON, SORT_BUTTON, rgba(55, 55, 55, 255));
|
||||
batch.fill(
|
||||
atlas,
|
||||
x + 1.0,
|
||||
y + 1.0,
|
||||
SORT_BUTTON - 2.0,
|
||||
SORT_BUTTON - 2.0,
|
||||
face,
|
||||
);
|
||||
for (i, w) in [5.0, 4.0, 3.0].into_iter().enumerate() {
|
||||
let by = y + 2.0 + 2.0 * i as f32;
|
||||
batch.fill(atlas, x + 2.0, by, w, 1.0, rgba(55, 55, 55, 255));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A left press on a sort button sorts its slots (true).
|
||||
pub(super) fn sort_press(&mut self) -> bool {
|
||||
let Some(r) = self.renderer.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let batch = HudBatch::new([r.config.width, r.config.height]);
|
||||
let (ox, oy) = self.inventory_origin(&batch);
|
||||
let (cx, cy) = self.cursor;
|
||||
let hit = self.sort_buttons().into_iter().find(|((x, y), _)| {
|
||||
let (x, y) = (ox + x, oy + y);
|
||||
cx >= x && cx < x + SORT_BUTTON && cy >= y && cy < y + SORT_BUTTON
|
||||
});
|
||||
let Some((_, slots)) = hit else {
|
||||
return false;
|
||||
};
|
||||
self.sort_slots(&slots);
|
||||
true
|
||||
}
|
||||
/// The sort key: sorts the part under the cursor (the container when
|
||||
/// the cursor is over no slot).
|
||||
pub(super) fn sort_key_press(&mut self, key: KeyCode) -> bool {
|
||||
let e = &self.settings.extras;
|
||||
if !e.sort || keybinds::key_code(&e.sort_key) != Some(key) || self.recipe_search_focused() {
|
||||
return false;
|
||||
}
|
||||
let buttons = self.sort_buttons();
|
||||
let hovered = self.inventory_target().0;
|
||||
let slots = buttons
|
||||
.iter()
|
||||
.find(|(_, slots)| hovered.is_some_and(|h| slots.contains(&h)))
|
||||
.or(buttons.first())
|
||||
.map(|(_, slots)| slots.clone());
|
||||
let Some(slots) = slots else {
|
||||
return false;
|
||||
};
|
||||
self.sort_slots(&slots);
|
||||
true
|
||||
}
|
||||
/// Sorts `slots` with ordinary left clicks (needs an empty hand).
|
||||
fn sort_slots(&mut self, slots: &[usize]) {
|
||||
if self.carried.is_some() {
|
||||
return;
|
||||
}
|
||||
let views: Vec<Option<ItemStack>> = slots.iter().map(|&s| self.slot_view(s)).collect();
|
||||
let clicks = {
|
||||
let names = |id: &str| self.res.names.item(id);
|
||||
let rank = |s: &ItemStack| {
|
||||
let order = self.creative_screen.order_of(s).unwrap_or(usize::MAX);
|
||||
(order, hover_name(&names, s))
|
||||
};
|
||||
let max = |s: &ItemStack| self.max_stack(s);
|
||||
inv_sort::plan(&views, &rank, &max)
|
||||
};
|
||||
for i in clicks {
|
||||
self.tweak_click(slots[i], 0, Input::Pickup);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Horizon's sorting extra (#332, `docs/extras.md`): the left clicks that
|
||||
//! sort a run of slots, starting and ending with an empty hand, as a player
|
||||
//! could click them, so a vanilla server accepts them. Partial stacks of
|
||||
//! one item merge first; then the stacks go in rank order (creative tab
|
||||
//! order, then name), full stacks before the partial one, empty slots last.
|
||||
use crate::items::ItemStack;
|
||||
|
||||
/// A stack's place in the order: its index in the creative tabs (items
|
||||
/// outside them after), then its name.
|
||||
pub type Rank = (usize, String);
|
||||
|
||||
/// A hand and slots under `AbstractContainerMenu.doClick`'s left `PICKUP`.
|
||||
struct Sim<'a> {
|
||||
slots: Vec<Option<ItemStack>>,
|
||||
hand: Option<ItemStack>,
|
||||
max: &'a dyn Fn(&ItemStack) -> u32,
|
||||
clicks: Vec<usize>,
|
||||
}
|
||||
impl Sim<'_> {
|
||||
fn click(&mut self, i: usize) {
|
||||
self.clicks.push(i);
|
||||
let slot = self.slots[i].take();
|
||||
match (self.hand.take(), slot) {
|
||||
// Take the stack, or put the hand's down.
|
||||
(None, s) => self.hand = s,
|
||||
(Some(h), None) => self.slots[i] = Some(h),
|
||||
// The same item: as much as fits joins the slot.
|
||||
(Some(mut h), Some(mut s)) if s.same_item_same_components(&h) => {
|
||||
let n = (self.max)(&s).saturating_sub(s.count).min(h.count);
|
||||
s.count += n;
|
||||
h.count -= n;
|
||||
self.slots[i] = Some(s);
|
||||
self.hand = (h.count > 0).then_some(h);
|
||||
}
|
||||
// Another item: they swap.
|
||||
(Some(h), Some(s)) => {
|
||||
self.slots[i] = Some(h);
|
||||
self.hand = Some(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn partial(&self, i: usize) -> Option<&ItemStack> {
|
||||
self.slots[i].as_ref().filter(|s| s.count < (self.max)(s))
|
||||
}
|
||||
}
|
||||
|
||||
/// The indices of `slots` to left-click, in order, to sort them. Empty
|
||||
/// when they are sorted already, or when the clicks couldn't reach the
|
||||
/// order (stacks over their maximum).
|
||||
pub fn plan(
|
||||
slots: &[Option<ItemStack>],
|
||||
rank: &dyn Fn(&ItemStack) -> Rank,
|
||||
max: &dyn Fn(&ItemStack) -> u32,
|
||||
) -> Vec<usize> {
|
||||
let n = slots.len();
|
||||
let mut sim = Sim {
|
||||
slots: slots.to_vec(),
|
||||
hand: None,
|
||||
max,
|
||||
clicks: Vec::new(),
|
||||
};
|
||||
// Merge: each later partial stack of the item tops up the first one;
|
||||
// what doesn't fit goes back.
|
||||
for i in 0..n {
|
||||
for j in i + 1..n {
|
||||
let Some(s) = sim.partial(i) else {
|
||||
break;
|
||||
};
|
||||
if !sim
|
||||
.partial(j)
|
||||
.is_some_and(|t| t.same_item_same_components(s))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
sim.click(j);
|
||||
sim.click(i);
|
||||
if sim.hand.is_some() {
|
||||
sim.click(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
let stacks: Vec<ItemStack> = sim.slots.iter().flatten().cloned().collect();
|
||||
let ranks: Vec<Rank> = stacks.iter().map(rank).collect();
|
||||
let mut order: Vec<usize> = (0..stacks.len()).collect();
|
||||
order.sort_by(|&a, &b| {
|
||||
ranks[a]
|
||||
.cmp(&ranks[b])
|
||||
.then(stacks[b].count.cmp(&stacks[a].count))
|
||||
});
|
||||
let target: Vec<Option<ItemStack>> = order
|
||||
.iter()
|
||||
.map(|&i| Some(stacks[i].clone()))
|
||||
.chain(std::iter::repeat(None))
|
||||
.take(n)
|
||||
.collect();
|
||||
// Order: each slot takes its stack from further on; what it held goes
|
||||
// where that stack was. A full stack clicked on the item's partial one
|
||||
// fills it and takes the rest, which comes to the same.
|
||||
for i in 0..n {
|
||||
if sim.slots[i] == target[i] {
|
||||
continue;
|
||||
}
|
||||
let Some(j) = (i + 1..n).find(|&j| sim.slots[j] == target[i]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
sim.click(j);
|
||||
sim.click(i);
|
||||
if sim.hand.is_some() {
|
||||
sim.click(j);
|
||||
}
|
||||
}
|
||||
if sim.hand.is_some() || sim.slots != target {
|
||||
return Vec::new();
|
||||
}
|
||||
sim.clicks
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::menu::{Input, Kind};
|
||||
|
||||
fn stack(item: &str, count: u32) -> Option<ItemStack> {
|
||||
Some(ItemStack {
|
||||
item: format!("minecraft:{item}").into(),
|
||||
count,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
})
|
||||
}
|
||||
fn rank(order: &'static [&'static str]) -> impl Fn(&ItemStack) -> Rank {
|
||||
move |s| {
|
||||
let id = s.item.trim_start_matches("minecraft:");
|
||||
let i = order.iter().position(|o| *o == id).unwrap_or(usize::MAX);
|
||||
(i, id.to_owned())
|
||||
}
|
||||
}
|
||||
fn max(s: &ItemStack) -> u32 {
|
||||
match &*s.item {
|
||||
"minecraft:ender_pearl" => 16,
|
||||
"minecraft:diamond_sword" => 1,
|
||||
_ => 64,
|
||||
}
|
||||
}
|
||||
const ORDER: &[&str] = &["stone", "dirt", "diamond_sword", "ender_pearl"];
|
||||
|
||||
#[test]
|
||||
fn merges_partial_stacks_then_orders_full_stacks_first() {
|
||||
let slots = vec![
|
||||
stack("ender_pearl", 3),
|
||||
None,
|
||||
stack("dirt", 40),
|
||||
stack("stone", 64),
|
||||
stack("dirt", 40),
|
||||
stack("ender_pearl", 15),
|
||||
stack("diamond_sword", 1),
|
||||
stack("zombie_head", 1),
|
||||
];
|
||||
let clicks = plan(&slots, &rank(ORDER), &max);
|
||||
let mut sim = Sim {
|
||||
slots: slots.clone(),
|
||||
hand: None,
|
||||
max: &max,
|
||||
clicks: Vec::new(),
|
||||
};
|
||||
for i in clicks {
|
||||
sim.click(i);
|
||||
}
|
||||
assert_eq!(sim.hand, None);
|
||||
assert_eq!(
|
||||
sim.slots,
|
||||
vec![
|
||||
stack("stone", 64),
|
||||
stack("dirt", 64),
|
||||
stack("dirt", 16),
|
||||
stack("diamond_sword", 1),
|
||||
stack("ender_pearl", 16),
|
||||
stack("ender_pearl", 2),
|
||||
stack("zombie_head", 1),
|
||||
None,
|
||||
]
|
||||
);
|
||||
// Sorted slots need no clicks.
|
||||
assert!(plan(&sim.slots, &rank(ORDER), &max).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clicks_sort_a_chest_in_the_menu_engine() {
|
||||
// The planned clicks replayed as left PICKUPs on a ChestMenu: the
|
||||
// engine (checked against the server jar) ends in the planned order.
|
||||
crate::menu::tests::with_menu(Kind::Chest(3), |env, menu| {
|
||||
let max = |s: &ItemStack| env.items.get(&s.item).map_or(64, |i| i.max_stack);
|
||||
let names = ["stone", "dirt", "ender_pearl", "oak_log", "snowball"];
|
||||
let mut seed = 7u32;
|
||||
for round in 0..40 {
|
||||
let slots: Vec<Option<ItemStack>> = (0..27)
|
||||
.map(|_| {
|
||||
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
|
||||
let pick = (seed >> 16) as usize % 8;
|
||||
let item = names.get(pick)?;
|
||||
let top = if *item == "ender_pearl" || *item == "snowball" {
|
||||
16
|
||||
} else {
|
||||
64
|
||||
};
|
||||
stack(item, 1 + (seed >> 8) % top)
|
||||
})
|
||||
.collect();
|
||||
for (i, s) in slots.iter().enumerate() {
|
||||
menu.set_slot(env, i, s.clone());
|
||||
}
|
||||
let clicks = plan(&slots, &rank(&["oak_log", "stone", "dirt"]), &max);
|
||||
for i in &clicks {
|
||||
menu.click(env, *i as i32, 0, Input::Pickup).unwrap();
|
||||
}
|
||||
assert_eq!(menu.carried, None, "round {round}");
|
||||
let after: Vec<Option<ItemStack>> =
|
||||
(0..27).map(|i| menu.slot(i).cloned()).collect();
|
||||
let total = |v: &[Option<ItemStack>], item: &str| -> u32 {
|
||||
v.iter()
|
||||
.flatten()
|
||||
.filter(|s| s.item.ends_with(item))
|
||||
.map(|s| s.count)
|
||||
.sum()
|
||||
};
|
||||
for item in names {
|
||||
assert_eq!(total(&slots, item), total(&after, item), "round {round}");
|
||||
}
|
||||
assert!(plan(&after, &rank(&["oak_log", "stone", "dirt"]), &max).is_empty());
|
||||
let items: Vec<&str> = after.iter().flatten().map(|s| &*s.item).collect();
|
||||
let mut sorted = items.clone();
|
||||
sorted.sort_by_key(|id| {
|
||||
rank(&["oak_log", "stone", "dirt"])(&stack(&id[10..], 1).unwrap())
|
||||
});
|
||||
assert_eq!(items, sorted, "round {round}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,7 @@ pub mod hud_layout;
|
||||
pub mod hud_overlays;
|
||||
pub mod hunger;
|
||||
pub mod input;
|
||||
pub mod inv_sort;
|
||||
pub mod inventory_effects;
|
||||
pub mod item_data;
|
||||
pub mod item_render;
|
||||
|
||||
@@ -1928,7 +1928,7 @@ impl Menu {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use crate::{banner::Banners, brewing::Brewing, crafting::Recipes};
|
||||
|
||||
@@ -1952,7 +1952,8 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
fn with_menu(kind: Kind, test: impl FnOnce(&Env, &mut Menu)) {
|
||||
/// A menu over the game's data (`.local/horizon-client`); skipped without it.
|
||||
pub(crate) fn with_menu(kind: Kind, test: impl FnOnce(&Env, &mut Menu)) {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client/26.3");
|
||||
if !root.join("items.json").exists() {
|
||||
|
||||
@@ -424,13 +424,12 @@ impl OptionsUi {
|
||||
ui.described_row(x, y, caption, "", 0.0, cost, text, cw - 60.0);
|
||||
ui.switch(id, control_x, cy, on);
|
||||
} else {
|
||||
let value = if item == extras::Item::ZoomKey
|
||||
&& self.selected_key == Some(extras::ZOOM_KEY)
|
||||
{
|
||||
"Press a key".to_owned()
|
||||
} else {
|
||||
item.value(&s.extras)
|
||||
};
|
||||
let value =
|
||||
if item.key_name().is_some() && self.selected_key == item.key_name() {
|
||||
"Press a key".to_owned()
|
||||
} else {
|
||||
item.value(&s.extras)
|
||||
};
|
||||
let bw = ui.button_width(&value, false).max(96.0);
|
||||
ui.described_row(x, y, caption, "", 0.0, cost, text, cw - bw - 24.0);
|
||||
ui.button(
|
||||
@@ -557,8 +556,8 @@ impl OptionsUi {
|
||||
}
|
||||
return events;
|
||||
}
|
||||
// A click anywhere stops waiting for the zoom key.
|
||||
if self.selected_key == Some(extras::ZOOM_KEY) {
|
||||
// A click anywhere stops waiting for an extra's key.
|
||||
if matches!(self.selected_key, Some(extras::ZOOM_KEY | extras::SORT_KEY)) {
|
||||
self.selected_key = None;
|
||||
}
|
||||
match self.horizon_target(s, atlas, x, y) {
|
||||
@@ -602,8 +601,8 @@ impl OptionsUi {
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Some(HRow::Page(_, _, page)) => self.open_page(*page),
|
||||
Some(HRow::Extra(extras::Item::ZoomKey)) => {
|
||||
self.selected_key = Some(extras::ZOOM_KEY);
|
||||
Some(HRow::Extra(item)) if item.key_name().is_some() => {
|
||||
self.selected_key = item.key_name();
|
||||
}
|
||||
Some(HRow::Extra(item)) => {
|
||||
item.cycle(&mut s.extras, right);
|
||||
|
||||
@@ -2050,9 +2050,7 @@ impl OptionsUi {
|
||||
.unwrap_or("key.keyboard.unknown")
|
||||
.to_owned()
|
||||
};
|
||||
if name == crate::extras::ZOOM_KEY {
|
||||
s.extras.zoom_key = value;
|
||||
} else {
|
||||
if !s.extras.set_key(name, value.clone()) {
|
||||
s.keys.set(name, &value);
|
||||
}
|
||||
return vec![Event::Changed];
|
||||
|
||||
+16
-2
@@ -1,7 +1,8 @@
|
||||
# Horizon extras
|
||||
|
||||
Optional conveniences built into the client: zoom, a minimap, an FPS counter, a
|
||||
keystroke overlay, auto-reconnect and Mouse Tweaks-style inventory controls. **Every one is off by default**: a fresh
|
||||
keystroke overlay, auto-reconnect, Mouse Tweaks-style inventory controls and
|
||||
inventory sorting. **Every one is off by default**: a fresh
|
||||
install looks and behaves exactly like vanilla 26.3, and turning an extra off
|
||||
again restores vanilla's behaviour completely.
|
||||
|
||||
@@ -15,7 +16,8 @@ again restores vanilla's behaviour completely.
|
||||
| Minimap colours, tiles and image | `crates/horizon-client/src/minimap.rs` |
|
||||
| Reconnect policy and backoff | `crates/horizon-client/src/reconnect.rs` |
|
||||
| Game glue (input hooks, per-frame update) | `crates/horizon-client/src/game/extras.rs` |
|
||||
| Mouse Tweaks-style controls | `crates/horizon-client/src/game/tweaks.rs` |
|
||||
| Mouse Tweaks-style controls, sort buttons | `crates/horizon-client/src/game/tweaks.rs` |
|
||||
| Sort order and its clicks | `crates/horizon-client/src/inv_sort.rs` (pure, unit tested) |
|
||||
| The settings page | `options_horizon.rs`: the **Extras** section of Horizon's Options |
|
||||
|
||||
`game.rs` only gets one-line hooks (key, wheel, mouse, frame, HUD), so the
|
||||
@@ -116,6 +118,18 @@ vanilla server sees nothing unusual. With the extra off, the hooks return at
|
||||
once and the screens click exactly as vanilla's (`tools/test_menu_click_parity.py`
|
||||
and the container screen tests are unchanged).
|
||||
|
||||
### Sorting (`sort`, default off; `sortKey`, unbound)
|
||||
- A small button right of the container's title (chests, barrels, ender
|
||||
chests, shulker boxes) and one right of the "Inventory" line (the main
|
||||
inventory; the hotbar is left alone). The key, when bound on the Extras
|
||||
page, sorts the part under the cursor (the container when over no slot).
|
||||
- Partial stacks of one item merge, then the stacks go in creative tab order
|
||||
(the search tab's), then by name; full stacks before the partial one,
|
||||
empty slots last. It needs an empty hand.
|
||||
- Done with ordinary left clicks planned by `inv_sort::plan`, so a vanilla
|
||||
server accepts it; a unit test replays the planned clicks through the menu
|
||||
engine on random chests.
|
||||
|
||||
## Shared rules
|
||||
|
||||
- All extras are hidden with F1 and drawn in the HUD layer: under screens, over
|
||||
|
||||
Reference in New Issue
Block a user