Merge pull request #1188 from ludovic111/fix/lan-guest-workstations-8
🤖 Agent: merged after integration wave 2 on the desktop (integ/w2 @ 38307d15): fmt, clippy, workspace + launcher tests, release build and every affected parity harness pass. main merged into the branch with the same resolution as the tested tree; verify passes on that head.
This commit is contained in:
@@ -82,12 +82,19 @@ fn main() -> horizon_client::Result<()> {
|
||||
let brewing = horizon_client::brewing::Brewing::load(root, &items);
|
||||
// The inventory menu never reads banner patterns.
|
||||
let banners = horizon_client::banner::Banners::default();
|
||||
let station_recipes = horizon_client::stations::StationRecipes::default();
|
||||
let enchantments = horizon_client::enchant::Enchantments::default();
|
||||
let names = horizon_client::creative::Names::default();
|
||||
let env = Env {
|
||||
items: &items,
|
||||
recipes: &recipes,
|
||||
brewing: &brewing,
|
||||
banners: &banners,
|
||||
station_recipes: &station_recipes,
|
||||
enchantments: &enchantments,
|
||||
names: &names,
|
||||
trade: None,
|
||||
maps: None,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for line in input.lines() {
|
||||
|
||||
@@ -11,8 +11,41 @@ use horizon_client::{
|
||||
items::Items,
|
||||
menu::{Env, Input, Kind, Menu},
|
||||
};
|
||||
use horizon_protocol::registry::Ids;
|
||||
use serde_json::Value;
|
||||
use std::{fs, path::Path};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
fs,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
/// The case's maps: (locked, scale) by id, and the next free id.
|
||||
#[derive(Default)]
|
||||
struct CaseMaps {
|
||||
maps: RefCell<HashMap<i32, (bool, u8)>>,
|
||||
next: Cell<i32>,
|
||||
}
|
||||
|
||||
impl horizon_client::menu::Maps for CaseMaps {
|
||||
fn state(&self, id: i32) -> Option<(bool, u8)> {
|
||||
self.maps.borrow().get(&id).copied()
|
||||
}
|
||||
|
||||
/// `MapItemSavedData.scaled` (unlocked, one scale up) or `locked`.
|
||||
fn derive(&self, id: i32, scale: bool) -> Option<i32> {
|
||||
let (_, s) = self.state(id)?;
|
||||
let new = self.next.get();
|
||||
self.next.set(new + 1);
|
||||
let made = if scale {
|
||||
(false, (s + 1).min(4))
|
||||
} else {
|
||||
(true, s)
|
||||
};
|
||||
self.maps.borrow_mut().insert(new, made);
|
||||
Some(new)
|
||||
}
|
||||
}
|
||||
|
||||
fn state(menu: &Menu) -> String {
|
||||
let slots: Vec<String> = (0..menu.slot_count())
|
||||
@@ -24,13 +57,21 @@ fn state(menu: &Menu) -> String {
|
||||
.iter()
|
||||
.map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref())))
|
||||
.collect();
|
||||
format!(
|
||||
let line = format!(
|
||||
"{} | {} |{data} | {} | {}",
|
||||
slots.join(" "),
|
||||
canon_stack(menu.carried.as_ref()),
|
||||
menu.drops.join(";"),
|
||||
equipped.join(";")
|
||||
)
|
||||
);
|
||||
if menu.kind() != Kind::Lectern {
|
||||
return line;
|
||||
}
|
||||
// No inventory slots: the inventory Take Book fills.
|
||||
let items: String = (0..36)
|
||||
.map(|i| format!(" {}", canon_stack(menu.player_item(i))))
|
||||
.collect();
|
||||
format!("{line} | inv{items}")
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
@@ -44,13 +85,28 @@ fn main() -> horizon_client::Result<()> {
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let brewing = horizon_client::brewing::Brewing::load(root, &items);
|
||||
let banners = horizon_client::banner::Banners::load(root);
|
||||
let station_recipes = horizon_client::stations::StationRecipes::load(root, &items);
|
||||
let enchantments = horizon_client::enchant::Enchantments::load(root);
|
||||
let names = horizon_client::creative::Names::load(root);
|
||||
let case_maps = CaseMaps::default();
|
||||
let env = Env {
|
||||
items: &items,
|
||||
recipes: &recipes,
|
||||
brewing: &brewing,
|
||||
banners: &banners,
|
||||
station_recipes: &station_recipes,
|
||||
enchantments: &enchantments,
|
||||
names: &names,
|
||||
trade: None,
|
||||
maps: Some(&case_maps),
|
||||
};
|
||||
// The mob effects' network ids (BeaconMenu.encodeEffect).
|
||||
let builtin = horizon_protocol::registry::Builtin::find(root)
|
||||
.and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok());
|
||||
let effects = builtin
|
||||
.as_ref()
|
||||
.and_then(|b| b.get("minecraft:mob_effect"))
|
||||
.cloned();
|
||||
let mut out = String::new();
|
||||
for line in input.lines() {
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
@@ -68,15 +124,41 @@ fn main() -> horizon_client::Result<()> {
|
||||
.unwrap_or(name),
|
||||
)
|
||||
.ok_or("menu kind")?;
|
||||
// [id, scale, locked] each; the level's new maps from 1000.
|
||||
case_maps.next.set(1000);
|
||||
*case_maps.maps.borrow_mut() = case["maps"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|m| {
|
||||
let id = m[0].as_i64().unwrap_or(0) as i32;
|
||||
(
|
||||
id,
|
||||
(
|
||||
m[2].as_bool().unwrap_or(false),
|
||||
m[1].as_u64().unwrap_or(0) as u8,
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut menu = Menu::new(kind);
|
||||
menu.creative = case["creative"].as_bool().unwrap_or(false);
|
||||
menu.levels = case["levels"].as_i64().unwrap_or(0) as i32;
|
||||
for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() {
|
||||
menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?);
|
||||
}
|
||||
menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?;
|
||||
for (i, item) in case["inventory"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
{
|
||||
menu.set_player_item(i, parse_stack(item.as_str().unwrap_or("-"))?);
|
||||
}
|
||||
menu.settle(&env);
|
||||
for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() {
|
||||
menu.data[i] = v.as_i64().unwrap_or(0) as i32;
|
||||
menu.set_data(i, v.as_i64().unwrap_or(0) as i32);
|
||||
}
|
||||
let mut furnace = furnace_kind.map(|kind| Furnace {
|
||||
kind,
|
||||
@@ -100,6 +182,26 @@ fn main() -> horizon_client::Result<()> {
|
||||
out += &format!("{}\n", state(&menu));
|
||||
continue;
|
||||
}
|
||||
// ServerboundRenameItemPacket: AnvilMenu.setItemName.
|
||||
"RENAME" => {
|
||||
menu.rename(&env, op[3].as_str().unwrap_or_default());
|
||||
out += &format!("{}\n", state(&menu));
|
||||
continue;
|
||||
}
|
||||
// ServerboundSetBeaconPacket: BeaconMenu.updateEffects.
|
||||
"SET_BEACON" => {
|
||||
fn power<'a>(ids: Option<&Ids>, v: &'a Value) -> Option<(i32, &'a str)> {
|
||||
let name = v.as_str()?;
|
||||
Some((ids?.id(name)?, name))
|
||||
}
|
||||
let (primary, secondary) = (
|
||||
power(effects.as_ref(), &op[3]),
|
||||
power(effects.as_ref(), &op[4]),
|
||||
);
|
||||
menu.beacon_update(&env, primary, secondary);
|
||||
out += &format!("{}\n", state(&menu));
|
||||
continue;
|
||||
}
|
||||
// ServerboundContainerSlotStateChangedPacket.
|
||||
"SLOT_STATE" => {
|
||||
if (0..9).contains(&slot) {
|
||||
|
||||
@@ -38,12 +38,19 @@ fn main() -> horizon_client::Result<()> {
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let brewing = horizon_client::brewing::Brewing::load(root, &items);
|
||||
let banners = horizon_client::banner::Banners::default();
|
||||
let station_recipes = horizon_client::stations::StationRecipes::default();
|
||||
let enchantments = horizon_client::enchant::Enchantments::default();
|
||||
let names = horizon_client::creative::Names::default();
|
||||
let env = Env {
|
||||
items: &items,
|
||||
recipes: &recipes,
|
||||
brewing: &brewing,
|
||||
banners: &banners,
|
||||
station_recipes: &station_recipes,
|
||||
enchantments: &enchantments,
|
||||
names: &names,
|
||||
trade: None,
|
||||
maps: None,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for (line, order) in cases.lines().zip(orders.lines()) {
|
||||
|
||||
@@ -239,10 +239,12 @@ fn main() -> horizon_client::Result<()> {
|
||||
let vanilla = fs::read_to_string(args.get(3).ok_or(usage)?)?;
|
||||
let items = Items::catalog(root)?;
|
||||
let enchantments = Enchantments::load(root);
|
||||
let names = horizon_client::creative::Names::default();
|
||||
let trades = Trades::load(root);
|
||||
let recipes = horizon_client::crafting::Recipes::load(root, &items)?;
|
||||
let brewing = horizon_client::brewing::Brewing::load(root, &items);
|
||||
let banners = horizon_client::banner::Banners::load(root);
|
||||
let station_recipes = horizon_client::stations::StationRecipes::default();
|
||||
let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)?
|
||||
.types
|
||||
.into_iter()
|
||||
@@ -378,7 +380,11 @@ fn main() -> horizon_client::Result<()> {
|
||||
recipes: &recipes,
|
||||
brewing: &brewing,
|
||||
banners: &banners,
|
||||
station_recipes: &station_recipes,
|
||||
enchantments: &enchantments,
|
||||
names: &names,
|
||||
trade: Some(&env_trade),
|
||||
maps: None,
|
||||
};
|
||||
trade(&mut out, name, &kv, &mut world, &env, origin)?;
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ pub struct Creative {
|
||||
search_index: Vec<SearchEntry>,
|
||||
}
|
||||
/// Display names from the pinned en_us language file.
|
||||
#[derive(Default)]
|
||||
pub struct Names {
|
||||
map: HashMap<String, String>,
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ pub struct ItemProps {
|
||||
/// `minecraft:brewing_fuel` present.
|
||||
pub brewing_fuel: bool,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct Enchantments {
|
||||
pub list: Vec<Enchantment>,
|
||||
index: HashMap<Arc<str>, usize>,
|
||||
|
||||
@@ -74,6 +74,7 @@ mod lan_entities;
|
||||
mod lan_mobs;
|
||||
mod lan_pvp;
|
||||
mod lan_screen;
|
||||
mod lan_stations;
|
||||
mod lan_trading;
|
||||
mod lan_waypoints;
|
||||
mod leads;
|
||||
@@ -119,6 +120,7 @@ mod recipe_book;
|
||||
mod remote;
|
||||
mod remote_objects;
|
||||
mod remote_projectiles;
|
||||
mod remote_stations;
|
||||
mod render_control;
|
||||
mod render_tick;
|
||||
mod respawn_anchor;
|
||||
@@ -2562,14 +2564,23 @@ impl Game<'_> {
|
||||
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
|
||||
1031 => Some(("minecraft:block.anvil.land", 0.3)),
|
||||
1505 => Some(("minecraft:item.bone_meal.use", 1.0)),
|
||||
1042 => Some(("minecraft:block.grindstone.use", 1.0)),
|
||||
1044 => Some(("minecraft:block.smithing_table.use", 1.0)),
|
||||
// LevelEvent.SOUND_PAGE_TURN (a lectern's page).
|
||||
1043 => Some(("minecraft:item.book.page_turn", 1.0)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((name, volume)) = sound {
|
||||
let pitch = if id == 1009 {
|
||||
2.6 + (self.world.random.next_float() - self.world.random.next_float())
|
||||
* 0.8
|
||||
} else {
|
||||
1.0
|
||||
let pitch = match id {
|
||||
1009 => {
|
||||
2.6 + (self.world.random.next_float()
|
||||
- self.world.random.next_float())
|
||||
* 0.8
|
||||
}
|
||||
1029 | 1030 | 1042 | 1043 | 1044 => {
|
||||
self.world.random.next_float() * 0.1 + 0.9
|
||||
}
|
||||
_ => 1.0,
|
||||
};
|
||||
self.audio.play(name, c, volume, pitch);
|
||||
}
|
||||
@@ -5442,6 +5453,17 @@ impl Game<'_> {
|
||||
.station
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.kind == stations::Kind::Merchant);
|
||||
let stonecutter_open = self
|
||||
.station
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.kind == stations::Kind::Stonecutter);
|
||||
let station_kind = self.station.as_ref().map(|s| s.kind);
|
||||
let grindstone_open = station_kind == Some(stations::Kind::Grindstone);
|
||||
let cartography_open = station_kind == Some(stations::Kind::Cartography);
|
||||
let anvil_open = station_kind == Some(stations::Kind::Anvil);
|
||||
let smithing_open = station_kind == Some(stations::Kind::Smithing);
|
||||
let enchanting_open = station_kind == Some(stations::Kind::Enchanting);
|
||||
let beacon_open = station_kind == Some(stations::Kind::Beacon);
|
||||
let (kind, game_of): (Kind, Vec<Option<usize>>) = if self.creative_tab_open() {
|
||||
// ItemPickerMenu: the display slots (clicked by the screen), then the hotbar.
|
||||
let mut v = vec![None; 45];
|
||||
@@ -5468,6 +5490,51 @@ impl Game<'_> {
|
||||
v.push(Some(stations::RESULT));
|
||||
v.extend((9..36).chain(0..9).map(Some));
|
||||
(Kind::Loom, v)
|
||||
} else if stonecutter_open {
|
||||
// StonecutterMenu: the input, the result, then the inventory.
|
||||
let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)];
|
||||
v.extend((9..36).chain(0..9).map(Some));
|
||||
(Kind::Stonecutter, v)
|
||||
} else if grindstone_open || cartography_open {
|
||||
// GrindstoneMenu and CartographyTableMenu: the two inputs, the
|
||||
// result, then the inventory.
|
||||
let mut v = vec![
|
||||
Some(stations::INPUT),
|
||||
Some(stations::INPUT + 1),
|
||||
Some(stations::RESULT),
|
||||
];
|
||||
v.extend((9..36).chain(0..9).map(Some));
|
||||
let kind = if grindstone_open {
|
||||
Kind::Grindstone
|
||||
} else {
|
||||
Kind::Cartography
|
||||
};
|
||||
(kind, v)
|
||||
} else if enchanting_open {
|
||||
// EnchantmentMenu: the item, the lapis, then the inventory.
|
||||
let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)];
|
||||
v.extend((9..36).chain(0..9).map(Some));
|
||||
(Kind::Enchanting, v)
|
||||
} else if beacon_open {
|
||||
// BeaconMenu: the payment, then the inventory.
|
||||
let mut v = vec![Some(stations::INPUT)];
|
||||
v.extend((9..36).chain(0..9).map(Some));
|
||||
(Kind::Beacon, v)
|
||||
} else if anvil_open || smithing_open {
|
||||
// ItemCombinerMenu: the inputs, the result, then the inventory.
|
||||
let inputs = if anvil_open { 2 } else { 3 };
|
||||
let mut v: Vec<Option<usize>> =
|
||||
(0..inputs).map(|i| Some(stations::INPUT + i)).collect();
|
||||
v.push(Some(stations::RESULT));
|
||||
v.extend((9..36).chain(0..9).map(Some));
|
||||
(
|
||||
if anvil_open {
|
||||
Kind::Anvil
|
||||
} else {
|
||||
Kind::Smithing
|
||||
},
|
||||
v,
|
||||
)
|
||||
} else {
|
||||
let (kind, map) = if self.container.is_some() {
|
||||
let size = self.container_size();
|
||||
@@ -5550,6 +5617,10 @@ impl Game<'_> {
|
||||
s.loom.patterns.clone(),
|
||||
)
|
||||
});
|
||||
let stone = self
|
||||
.station
|
||||
.as_ref()
|
||||
.map(|s| (s.selected.map_or(-1, |i| i as i32), s.stone.clone()));
|
||||
let crafter_data = match self.container_kind() {
|
||||
Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)),
|
||||
_ => None,
|
||||
@@ -5563,6 +5634,18 @@ impl Game<'_> {
|
||||
if let Some((s, mob)) = session.as_mut() {
|
||||
self.merchant_sync_in(s, *mob);
|
||||
}
|
||||
// The cartography table reads and makes the level's maps; a
|
||||
// server's (the client menu's ContainerLevelAccess.NULL) doesn't.
|
||||
let level_maps = (kind == Kind::Cartography && self.remote.is_none()).then(|| {
|
||||
let held: Vec<ItemStack> = before
|
||||
.iter()
|
||||
.flatten()
|
||||
.chain(self.inventory.iter().flatten())
|
||||
.chain(self.carried.iter())
|
||||
.cloned()
|
||||
.collect();
|
||||
self.level_maps(&held)
|
||||
});
|
||||
let next_map = if merchant_open { self.peek_map_id() } else { 0 };
|
||||
let tag = |t: &str| self.structure_tag(t);
|
||||
let maps = trading::GameMaps {
|
||||
@@ -5581,10 +5664,21 @@ impl Game<'_> {
|
||||
recipes: self.res.recipes(),
|
||||
brewing: &self.res.stations().brewing,
|
||||
banners: &self.res.stations().banners,
|
||||
station_recipes: &self.res.stations().recipes,
|
||||
enchantments: &self.res.stations().enchantments,
|
||||
names: &self.pack.names,
|
||||
trade: Some(&trade_env),
|
||||
maps: level_maps
|
||||
.as_ref()
|
||||
.map(|m| m as &dyn horizon_client::menu::Maps),
|
||||
};
|
||||
menu.creative = creative;
|
||||
menu.selected = self.selected;
|
||||
menu.levels = self.experience.level;
|
||||
if anvil_open {
|
||||
// The rename box as AnvilScreen.onNameChanged gives it to the menu.
|
||||
menu.anvil.name = self.station.as_ref().map(|s| self.anvil_item_name(s));
|
||||
}
|
||||
for (i, stack) in before.iter().enumerate() {
|
||||
menu.set_slot(&env, i, stack.clone());
|
||||
}
|
||||
@@ -5602,6 +5696,25 @@ impl Game<'_> {
|
||||
menu.loom_patterns = patterns;
|
||||
menu.set_slot(&env, 3, before[3].clone());
|
||||
}
|
||||
if kind == Kind::Stonecutter
|
||||
&& let Some((selected, state)) = stone
|
||||
{
|
||||
// The same: the list and selection between clicks, then the result.
|
||||
menu.data[0] = selected;
|
||||
menu.stone = state;
|
||||
menu.set_slot(&env, 1, before[1].clone());
|
||||
}
|
||||
if kind == Kind::Enchanting
|
||||
&& let Some(s) = self.station.as_ref()
|
||||
{
|
||||
// The offers between clicks (what copying the slots in flagged is not a change).
|
||||
menu.enchant_changed = false;
|
||||
for i in 0..3 {
|
||||
menu.data[i] = s.offers.costs[i];
|
||||
menu.data[7 + i] = s.offers.clues[i].as_ref().map_or(-1, |(_, l)| *l as i32);
|
||||
}
|
||||
menu.data[3] = self.level.xp_seed;
|
||||
}
|
||||
if let Some((disabled, triggered)) = crafter_data {
|
||||
for (i, d) in disabled.iter().enumerate() {
|
||||
menu.data[i] = i32::from(*d);
|
||||
@@ -5656,10 +5769,37 @@ impl Game<'_> {
|
||||
s.loom.selected = usize::try_from(menu.data[0]).ok();
|
||||
s.loom.patterns = std::mem::take(&mut menu.loom_patterns);
|
||||
}
|
||||
for sound in sounds {
|
||||
self.loom_sound(sound);
|
||||
// A server's loom plays its own sounds (the client's menu has no level).
|
||||
for sound in sounds.into_iter().filter(|_| !predicting) {
|
||||
self.station_sound(sound);
|
||||
}
|
||||
self.loom_screen_changed();
|
||||
} else if kind == Kind::Cartography {
|
||||
for sound in sounds.into_iter().filter(|_| !predicting) {
|
||||
self.station_sound(sound);
|
||||
}
|
||||
} else if kind == Kind::Stonecutter {
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
s.selected = usize::try_from(menu.data[0]).ok();
|
||||
s.stone = std::mem::take(&mut menu.stone);
|
||||
s.stonecutter_changed();
|
||||
}
|
||||
for sound in sounds.into_iter().filter(|_| !predicting) {
|
||||
self.station_sound(sound);
|
||||
}
|
||||
}
|
||||
if let Some(amount) = menu.ground.take().filter(|_| !predicting)
|
||||
&& let Some(pos) = self.station.as_ref().map(|s| s.pos)
|
||||
{
|
||||
self.grindstone_taken(pos, amount);
|
||||
}
|
||||
if kind == Kind::Anvil || kind == Kind::Smithing {
|
||||
self.combiner_session_end(&menu, predicting);
|
||||
}
|
||||
if kind == Kind::Enchanting && (menu.enchant_changed || before[0] != menu.slot(0).cloned())
|
||||
{
|
||||
// EnchantmentMenu.slotsChanged: new offers for the item.
|
||||
self.station_changed();
|
||||
}
|
||||
if kind == Kind::CrafterBlock
|
||||
&& let Some(BlockEntity::Crafter(c)) = self
|
||||
@@ -5687,6 +5827,9 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
self.apply_equipment();
|
||||
if let Some(maps) = level_maps {
|
||||
self.register_made_maps(maps);
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar
|
||||
|
||||
@@ -15,6 +15,7 @@ use horizon_client::{
|
||||
mesher::Vertex,
|
||||
mobs::render::{DYE, DYE_NAMES},
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Serverbound as S};
|
||||
|
||||
/// The beacon screen is 54 px wider than the 176-px menus it shares an origin with.
|
||||
pub(super) const SHIFT: f32 = -27.0;
|
||||
@@ -35,9 +36,6 @@ const PAYMENT: [&str; 5] = [
|
||||
"minecraft:diamond",
|
||||
"minecraft:netherite_ingot",
|
||||
];
|
||||
pub(super) fn is_payment(item: &str) -> bool {
|
||||
PAYMENT.contains(&item)
|
||||
}
|
||||
/// `BeaconMenu.PaymentSlot` and the player inventory, relative to the 176 origin.
|
||||
pub(super) fn slot_position(i: usize) -> Option<(f32, f32)> {
|
||||
Some(match i {
|
||||
@@ -171,7 +169,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
fn beacon_sound(&mut self, p: [i32; 3], sound: &str) {
|
||||
pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) {
|
||||
let at = [
|
||||
f64::from(p[0]) + 0.5,
|
||||
f64::from(p[1]) + 0.5,
|
||||
@@ -255,9 +253,13 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
fn beacon_levels(&self) -> i32 {
|
||||
let Some(pos) = self.station.as_ref().map(|s| s.pos) else {
|
||||
let Some(s) = self.station.as_ref() else {
|
||||
return 0;
|
||||
};
|
||||
if let Some(levels) = s.beacon_levels {
|
||||
return levels;
|
||||
}
|
||||
let pos = s.pos;
|
||||
match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) {
|
||||
Some(BlockEntity::Beacon(b)) => b.levels,
|
||||
_ => 0,
|
||||
@@ -346,8 +348,16 @@ impl Game<'_> {
|
||||
self.screen = super::Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
/// `BeaconMenu.updateEffects`: spend the payment and set the powers.
|
||||
/// `BeaconMenu.updateEffects`: spend the payment and set the powers. On
|
||||
/// a server, `BeaconScreen`'s confirm button sends them
|
||||
/// (`ServerboundSetBeaconPacket`) and the server's menu does it.
|
||||
fn confirm_beacon(&mut self, sel: [Option<usize>; 2]) {
|
||||
if self.remote.is_some() {
|
||||
let id = |e: Option<usize>| e.and_then(|e| self.remote_effect_network_id(EFFECTS[e].0));
|
||||
let (primary, secondary) = (id(sel[0]), id(sel[1]));
|
||||
self.send(S::SetBeacon(play::SetBeacon { primary, secondary }));
|
||||
return;
|
||||
}
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -9,6 +9,7 @@ use horizon_client::{
|
||||
hud::{HudBatch, rgba},
|
||||
item_data::WrittenBook,
|
||||
items::ItemStack,
|
||||
menu::{Kind, Menu},
|
||||
text::Text,
|
||||
ui,
|
||||
};
|
||||
@@ -89,6 +90,17 @@ impl Game<'_> {
|
||||
self.capture(false);
|
||||
}
|
||||
pub(super) fn close_book(&mut self) {
|
||||
// A server's lectern: LecternScreen's menu closes (closeContainer).
|
||||
if matches!(
|
||||
self.book,
|
||||
Some(BookScreen::View {
|
||||
lectern: Some(_),
|
||||
..
|
||||
})
|
||||
) && self.remote.is_some()
|
||||
{
|
||||
self.remote_close_container();
|
||||
}
|
||||
self.book = None;
|
||||
self.capture(true);
|
||||
}
|
||||
@@ -319,38 +331,25 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Some(BookScreen::View {
|
||||
pages,
|
||||
page,
|
||||
lectern,
|
||||
}) => {
|
||||
let before = *page;
|
||||
lectern: Some(key), ..
|
||||
}) => lectern_page = Some(*key),
|
||||
Some(BookScreen::View { pages, page, .. }) => {
|
||||
if forward && *page + 1 < pages.len() {
|
||||
*page += 1;
|
||||
} else if !forward && *page > 0 {
|
||||
*page -= 1;
|
||||
}
|
||||
if *page != before
|
||||
&& let Some(pos) = *lectern
|
||||
{
|
||||
lectern_page = Some((pos, *page));
|
||||
}
|
||||
}
|
||||
None => return,
|
||||
}
|
||||
// LecternScreen's page buttons click the menu's (1 back, 2 forward);
|
||||
// the page turns with the server's data slot and level event 1043.
|
||||
if let Some(key) = lectern_page {
|
||||
self.lectern_button(key, if forward { 2 } else { 1 });
|
||||
return;
|
||||
}
|
||||
self.audio
|
||||
.play("minecraft:item.book.page_turn", None, 1.0, 1.0);
|
||||
if let Some((pos, page)) = lectern_page {
|
||||
self.set_lectern_page(pos, page as i32);
|
||||
}
|
||||
}
|
||||
/// `LecternBlockEntity.setPage` and `LecternBlock.signalPageChange`.
|
||||
fn set_lectern_page(&mut self, key: (i32, i32, i32), page: i32) {
|
||||
if let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) {
|
||||
l.page = page;
|
||||
}
|
||||
self.set_lectern_powered(key, true);
|
||||
self.lectern_pulses.push((key, 2));
|
||||
self.container_changed(key);
|
||||
}
|
||||
fn set_lectern_powered(&mut self, key: (i32, i32, i32), powered: bool) {
|
||||
self.set_lectern_property(key, "powered", powered);
|
||||
@@ -380,6 +379,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// The 2-tick pulses of turned lecterns.
|
||||
pub(super) fn tick_lecterns(&mut self) {
|
||||
self.follow_lectern();
|
||||
let mut done = Vec::new();
|
||||
for (key, left) in &mut self.lectern_pulses {
|
||||
*left -= 1;
|
||||
@@ -452,6 +452,7 @@ impl Game<'_> {
|
||||
.or_else(|| data.map(|d| d.writable_pages.clone()))
|
||||
.unwrap_or_default();
|
||||
let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1));
|
||||
self.stats.custom("interact_with_lectern", 1);
|
||||
self.open_book(BookScreen::View {
|
||||
pages,
|
||||
page,
|
||||
@@ -459,24 +460,189 @@ impl Game<'_> {
|
||||
});
|
||||
true
|
||||
}
|
||||
/// `LecternMenu` "Take Book".
|
||||
fn take_lectern_book(&mut self, key: (i32, i32, i32)) {
|
||||
let book = match self.world.block_entities.get_mut(&key) {
|
||||
Some(BlockEntity::Lectern(l)) => {
|
||||
l.page = 0;
|
||||
l.book.take()
|
||||
/// A `LecternMenu` button of the open lectern screen: on a server it is
|
||||
/// sent (`handleInventoryButtonClick`); here the lectern's menu takes it
|
||||
/// with the player's inventory, and the screen follows the block entity.
|
||||
fn lectern_button(&mut self, key: (i32, i32, i32), id: i32) {
|
||||
if self.remote.is_some() {
|
||||
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) {
|
||||
self.send(
|
||||
horizon_protocol::packets::play::Serverbound::ContainerButtonClick(
|
||||
horizon_protocol::packets::play::ContainerButtonClick {
|
||||
container: *container,
|
||||
button: id,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(book) = book
|
||||
&& let Some(rest) = self.give(book)
|
||||
&& let Some(eye) = self.eye_position()
|
||||
{
|
||||
self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40);
|
||||
return;
|
||||
}
|
||||
let Some(mut menu) = self.lectern_menu(key) else {
|
||||
return;
|
||||
};
|
||||
for i in 0..36 {
|
||||
menu.set_player_item(i, self.inventory[i].clone());
|
||||
}
|
||||
menu.set_player_item(40, self.offhand.clone());
|
||||
menu.creative = self.creative;
|
||||
menu.selected = self.selected;
|
||||
menu.may_build = self.may_build();
|
||||
if !menu.button(&self.menu_env(), id) {
|
||||
return;
|
||||
}
|
||||
for i in 0..36 {
|
||||
self.inventory[i] = menu.player_item(i).cloned();
|
||||
}
|
||||
self.offhand = menu.player_item(40).cloned();
|
||||
for stack in std::mem::take(&mut menu.dropped) {
|
||||
self.player_drop(stack);
|
||||
}
|
||||
self.lectern_menu_done(key, &menu);
|
||||
self.follow_lectern();
|
||||
}
|
||||
/// The `book` control command: a button of the open book or lectern
|
||||
/// screen (the page arrows, Take Book, Done), then its page.
|
||||
pub(super) fn book_control(
|
||||
&mut self,
|
||||
action: Option<&str>,
|
||||
) -> horizon_client::Result<serde_json::Value> {
|
||||
let lectern = match &self.book {
|
||||
Some(BookScreen::View { lectern, .. }) => *lectern,
|
||||
Some(BookScreen::Edit { .. }) => None,
|
||||
None => return Err("no book is open".into()),
|
||||
};
|
||||
match action {
|
||||
None => {}
|
||||
Some("next") => self.turn_page(true),
|
||||
Some("back") => self.turn_page(false),
|
||||
Some("take") => match lectern {
|
||||
Some(key) => self.lectern_button(key, 3),
|
||||
None => return Err("not a lectern".into()),
|
||||
},
|
||||
Some("done") => self.close_book(),
|
||||
Some(other) => return Err(format!("unknown book button {other}").into()),
|
||||
}
|
||||
Ok(match &self.book {
|
||||
Some(BookScreen::View {
|
||||
pages,
|
||||
page,
|
||||
lectern,
|
||||
}) => serde_json::json!({
|
||||
"page": page, "pages": pages.len(), "lectern": lectern.map(|k| [k.0, k.1, k.2]),
|
||||
}),
|
||||
Some(BookScreen::Edit { pages, page, .. }) => {
|
||||
serde_json::json!({ "page": page, "pages": pages.len(), "lectern": null })
|
||||
}
|
||||
None => serde_json::json!({ "closed": true }),
|
||||
})
|
||||
}
|
||||
/// A server's `minecraft:lectern` menu: LecternScreen, its book and
|
||||
/// page to come (`remote_lectern_book`, `remote_lectern_page`).
|
||||
pub(super) fn remote_open_lectern(&mut self, key: (i32, i32, i32)) {
|
||||
self.open_book(BookScreen::View {
|
||||
pages: Vec::new(),
|
||||
page: 0,
|
||||
lectern: Some(key),
|
||||
});
|
||||
}
|
||||
/// `LecternScreen.bookChanged`: the menu's book slot.
|
||||
pub(super) fn remote_lectern_book(&mut self, book: Option<ItemStack>) {
|
||||
if let Some(BookScreen::View {
|
||||
lectern: Some(_),
|
||||
pages,
|
||||
page,
|
||||
}) = self.book.as_mut()
|
||||
{
|
||||
let data = book.as_ref().and_then(ItemStack::data);
|
||||
*pages = data
|
||||
.and_then(|d| d.written.as_ref().map(|w| w.pages.clone()))
|
||||
.or_else(|| data.map(|d| d.writable_pages.clone()))
|
||||
.unwrap_or_default();
|
||||
*page = (*page).min(pages.len().saturating_sub(1));
|
||||
}
|
||||
}
|
||||
/// `LecternScreen.pageChanged`: the menu's page data slot.
|
||||
pub(super) fn remote_lectern_page(&mut self, value: i32) {
|
||||
if let Some(BookScreen::View {
|
||||
lectern: Some(_),
|
||||
pages,
|
||||
page,
|
||||
}) = self.book.as_mut()
|
||||
{
|
||||
*page = (value.max(0) as usize).min(pages.len().saturating_sub(1));
|
||||
}
|
||||
}
|
||||
/// The server closed its lectern menu; false when none is open.
|
||||
pub(super) fn remote_lectern_closed(&mut self) -> bool {
|
||||
if !matches!(
|
||||
self.book,
|
||||
Some(BookScreen::View {
|
||||
lectern: Some(_),
|
||||
..
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.menu = None;
|
||||
r.menu_title = None;
|
||||
}
|
||||
self.book = None;
|
||||
self.capture(true);
|
||||
true
|
||||
}
|
||||
/// `LecternMenu` over the lectern at `key` (the menu engine, for the
|
||||
/// local player and LAN guests alike): its book and page.
|
||||
pub(super) fn lectern_menu(&self, key: (i32, i32, i32)) -> Option<Menu> {
|
||||
let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get(&key) else {
|
||||
return None;
|
||||
};
|
||||
let mut menu = Menu::new(Kind::Lectern);
|
||||
menu.set_slot(&self.menu_env(), 0, l.book.clone());
|
||||
menu.data[0] = l.page;
|
||||
Some(menu)
|
||||
}
|
||||
/// The lectern menu's book and page back in the block entity: a new page
|
||||
/// is `LecternBlock.signalPageChange` (the 2-tick pulse, level event
|
||||
/// 1043), a book gone `onBookItemRemove` (`resetBookState`).
|
||||
pub(super) fn lectern_menu_done(&mut self, key: (i32, i32, i32), menu: &Menu) {
|
||||
let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) else {
|
||||
return;
|
||||
};
|
||||
let (had, before) = (l.book.is_some(), l.page);
|
||||
l.book = menu.slot(0).cloned();
|
||||
l.page = menu.data[0];
|
||||
if had && l.book.is_none() {
|
||||
self.set_lectern_powered(key, false);
|
||||
self.set_lectern_property(key, "has_book", false);
|
||||
self.container_changed(key);
|
||||
} else if menu.data[0] != before {
|
||||
self.set_lectern_powered(key, true);
|
||||
self.lectern_pulses.push((key, 2));
|
||||
self.level_event_at(1043, [key.0, key.1, key.2], 0);
|
||||
self.container_changed(key);
|
||||
}
|
||||
}
|
||||
/// The open lectern screen follows its block entity (`LecternScreen`'s
|
||||
/// menu listener): the page, and closing once the book is gone.
|
||||
pub(super) fn follow_lectern(&mut self) {
|
||||
let Some(BookScreen::View {
|
||||
lectern: Some(key),
|
||||
page,
|
||||
pages,
|
||||
}) = self.book.as_mut()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
match self.world.block_entities.get(key) {
|
||||
Some(BlockEntity::Lectern(l)) if l.book.is_some() => {
|
||||
*page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1));
|
||||
}
|
||||
_ => self.close_book(),
|
||||
}
|
||||
self.set_lectern_property(key, "has_book", false);
|
||||
self.container_changed(key);
|
||||
self.close_book();
|
||||
}
|
||||
pub(super) fn book_click(&mut self, size: [u32; 2]) {
|
||||
let b = HudBatch::new(size);
|
||||
@@ -537,7 +703,8 @@ impl Game<'_> {
|
||||
self.close_book();
|
||||
} else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) {
|
||||
click(self);
|
||||
self.take_lectern_book(key);
|
||||
// LecternScreen's Take Book: the menu's button 3.
|
||||
self.lectern_button(key, 3);
|
||||
}
|
||||
} else if inside((w - 200.0) / 2.0, 196.0, 200.0, 20.0) {
|
||||
click(self);
|
||||
|
||||
@@ -1,70 +1,80 @@
|
||||
//! The cartography table (`CartographyTableMenu`, `CartographyTableScreen`):
|
||||
//! zooming a map out with paper, cloning it with an empty map, locking it
|
||||
//! with a glass pane, the post-processing on take (`MapItem.scaleMap`,
|
||||
//! `lockMap`) and the preview with its error and lock sprites.
|
||||
//! The cartography table (`CartographyTableMenu` on the menu engine,
|
||||
//! `CartographyTableScreen`): zooming a map out with paper, cloning it with
|
||||
//! an empty map, locking it with a glass pane. The engine reads the level's
|
||||
//! maps through `LevelMaps`; the scaled and locked copies a take makes
|
||||
//! (`MapItem.scaleMap`, `lockMap`) are registered after the click. The
|
||||
//! screen draws the preview with its error and lock sprites.
|
||||
use super::{
|
||||
Game,
|
||||
maps::{MapData, map_id},
|
||||
stations::Station,
|
||||
};
|
||||
use horizon_client::{hud::HudBatch, items::ItemStack};
|
||||
use horizon_client::{hud::HudBatch, items::ItemStack, menu::Maps};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
};
|
||||
|
||||
/// The level's maps as a menu sees them (`ContainerLevelAccess`): the
|
||||
/// states of the maps the click can reach, and the copies it makes.
|
||||
pub(super) struct LevelMaps {
|
||||
states: RefCell<HashMap<i32, (bool, u8)>>,
|
||||
next_id: Cell<i32>,
|
||||
/// (new id, source id, scaled) for each copy made.
|
||||
made: RefCell<Vec<(i32, i32, bool)>>,
|
||||
}
|
||||
|
||||
impl Maps for LevelMaps {
|
||||
fn state(&self, id: i32) -> Option<(bool, u8)> {
|
||||
self.states.borrow().get(&id).copied()
|
||||
}
|
||||
|
||||
fn derive(&self, id: i32, scale: bool) -> Option<i32> {
|
||||
let (_, s) = self.state(id)?;
|
||||
let new = self.next_id.get();
|
||||
self.next_id.set(new + 1);
|
||||
let made = if scale {
|
||||
(false, (s + 1).min(4))
|
||||
} else {
|
||||
(true, s)
|
||||
};
|
||||
self.states.borrow_mut().insert(new, made);
|
||||
self.made.borrow_mut().push((new, id, scale));
|
||||
Some(new)
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `setupResultSlot`.
|
||||
pub(super) fn cartography_result(&self, s: &Station) -> Option<ItemStack> {
|
||||
let (map, extra) = (s.inputs[0].as_ref()?, s.inputs[1].as_ref()?);
|
||||
let data = self.maps.data.get(&map_id(map)?)?;
|
||||
match &*extra.item {
|
||||
"minecraft:paper" if !data.locked && data.scale < 4 => Some(ItemStack {
|
||||
count: 1,
|
||||
..map.clone()
|
||||
}),
|
||||
"minecraft:glass_pane" if !data.locked => Some(ItemStack {
|
||||
count: 1,
|
||||
..map.clone()
|
||||
}),
|
||||
"minecraft:map" => Some(ItemStack {
|
||||
count: 2,
|
||||
..map.clone()
|
||||
}),
|
||||
_ => None,
|
||||
/// The maps of `stacks` (loaded as needed) for a menu over this level.
|
||||
pub(super) fn level_maps<'s>(
|
||||
&mut self,
|
||||
stacks: impl IntoIterator<Item = &'s ItemStack>,
|
||||
) -> LevelMaps {
|
||||
let ids: Vec<i32> = stacks.into_iter().filter_map(map_id).collect();
|
||||
let mut states = HashMap::new();
|
||||
for id in ids {
|
||||
if let Some(m) = self.map(id) {
|
||||
states.insert(id, (m.locked, m.scale));
|
||||
}
|
||||
}
|
||||
LevelMaps {
|
||||
states: RefCell::new(states),
|
||||
next_id: Cell::new(self.peek_map_id()),
|
||||
made: RefCell::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
/// `onCraftedPostProcess` for the taken result: a scaled or locked copy
|
||||
/// under a new map id. Also spends the inputs' extra item kind check.
|
||||
pub(super) fn cartography_post(&mut self, mut result: ItemStack) -> ItemStack {
|
||||
let extra = self
|
||||
.station
|
||||
.as_ref()
|
||||
.and_then(|s| s.inputs[1].as_ref())
|
||||
.map(|e| e.item.clone());
|
||||
let Some(id) = map_id(&result) else {
|
||||
return result;
|
||||
};
|
||||
let new = match extra.as_deref() {
|
||||
Some("minecraft:paper") => self.map(id).map(|m| m.scaled()),
|
||||
Some("minecraft:glass_pane") => self.map(id).map(|m| m.locked_copy()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(data) = new {
|
||||
let new_id = self.new_map_id(data);
|
||||
result.data_mut().map_id = Some(new_id);
|
||||
|
||||
/// The scaled and locked copies a menu made (`level.setMapData`).
|
||||
pub(super) fn register_made_maps(&mut self, maps: LevelMaps) {
|
||||
for (id, source, scale) in maps.made.into_inner() {
|
||||
let Some(data) = self
|
||||
.map(source)
|
||||
.map(|m| if scale { m.scaled() } else { m.locked_copy() })
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let new = self.new_map_id(data);
|
||||
debug_assert_eq!(new, id, "map ids follow peek_map_id");
|
||||
}
|
||||
result
|
||||
}
|
||||
/// The take sound (once per tick).
|
||||
pub(super) fn cartography_taken(&mut self, pos: [i32; 3]) {
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
self.audio.play(
|
||||
"minecraft:ui.cartography_table.take_result",
|
||||
Some(at),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
/// `CartographyTableScreen.extractBackground` after the background.
|
||||
pub(super) fn draw_cartography(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) {
|
||||
|
||||
@@ -523,13 +523,22 @@ impl Game<'_> {
|
||||
Screen::Inventory if self.recipe_search_focused() => {
|
||||
self.recipe_text(Some(text), false)
|
||||
}
|
||||
// The anvil's rename box.
|
||||
Screen::Inventory
|
||||
if self
|
||||
.station
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.kind == super::stations::Kind::Anvil) =>
|
||||
{
|
||||
self.station_text(Some(text), false)
|
||||
}
|
||||
Screen::Creative if self.creative_screen.tab().search => {
|
||||
// As typed: replaces a selected query, keeps the length limit.
|
||||
self.creative_search_edit(Some(text), false)
|
||||
}
|
||||
_ => {
|
||||
return Err(
|
||||
"type needs the chat screen (key t tap), the language search, the creative search or World Options".into(),
|
||||
"type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,10 @@ pub(super) struct GuestPlay {
|
||||
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
|
||||
/// The inventory menu and the crafting table the guest crafts in.
|
||||
pub(super) crafting: super::lan_crafting::GuestCrafting,
|
||||
/// The workstation menu the guest has open (game/lan_stations.rs).
|
||||
pub(super) station: Option<super::lan_stations::GuestStation>,
|
||||
/// The lectern the guest reads (game/lan_stations.rs).
|
||||
pub(super) lectern: Option<super::lan_stations::GuestLectern>,
|
||||
/// What the guest's body was given for its effects and enchantments.
|
||||
potions: super::potions::BodyPotions,
|
||||
/// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw.
|
||||
@@ -476,7 +480,13 @@ impl Game<'_> {
|
||||
self.container = container;
|
||||
self.screen = screen;
|
||||
self.sign_edit = host_sign;
|
||||
self.book = host_book;
|
||||
// A lectern the guest's use opened (LecternBlock.openScreen).
|
||||
let guest_lectern = match std::mem::replace(&mut self.book, host_book) {
|
||||
Some(super::books::BookScreen::View {
|
||||
lectern: Some(key), ..
|
||||
}) => Some(key),
|
||||
_ => None,
|
||||
};
|
||||
self.command_block_screen = host_command_block;
|
||||
self.mount_menu = host_mount_menu;
|
||||
self.keys = host_keys;
|
||||
@@ -573,6 +583,9 @@ impl Game<'_> {
|
||||
if let Some(station) = opened_station {
|
||||
self.lan_station_opened(host, conn, station);
|
||||
}
|
||||
if let Some(key) = guest_lectern {
|
||||
self.lan_open_lectern(host, conn, key);
|
||||
}
|
||||
if opened_table {
|
||||
self.lan_open_crafting(host, conn);
|
||||
}
|
||||
@@ -639,6 +652,13 @@ impl Game<'_> {
|
||||
_ => ("minecraft:furnace", "container.furnace"),
|
||||
};
|
||||
(menu, title, Slots::Block(pos))
|
||||
} else if let Some(BlockEntity::Crafter(_)) = self.world.block_entities.get(&pos) {
|
||||
// CrafterBlock.useWithoutItem: CrafterMenu over the block entity.
|
||||
(
|
||||
"minecraft:crafter_3x3",
|
||||
"container.crafter",
|
||||
Slots::Block(pos),
|
||||
)
|
||||
} else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) {
|
||||
// BrewingStandBlock.useWithoutItem: BrewingStandMenu.
|
||||
(
|
||||
@@ -681,6 +701,7 @@ impl Game<'_> {
|
||||
};
|
||||
// ServerPlayer.openMenu closes the menu that was open.
|
||||
self.guest_container_closed(host, conn);
|
||||
self.lan_station_closed(host, conn, None);
|
||||
host.hub.open_container(
|
||||
conn,
|
||||
menu,
|
||||
@@ -915,6 +936,16 @@ impl Game<'_> {
|
||||
S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {}
|
||||
S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {}
|
||||
S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {}
|
||||
S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {}
|
||||
S::ContainerClick(p) if self.lan_lectern_click(host, conn, &p) => {}
|
||||
S::ContainerButtonClick(p) => {
|
||||
self.lan_station_button(host, conn, p.container, p.button);
|
||||
}
|
||||
S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name),
|
||||
S::ContainerSlotStateChanged(p) => {
|
||||
self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled);
|
||||
}
|
||||
S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary),
|
||||
S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item),
|
||||
S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
@@ -922,7 +953,10 @@ impl Game<'_> {
|
||||
self.drop_guest_items(host, gi, vec![c]);
|
||||
}
|
||||
}
|
||||
S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => {
|
||||
S::ContainerClose(p)
|
||||
if self.lan_crafting_closed(host, conn, Some(p.container))
|
||||
|| self.lan_station_closed(host, conn, Some(p.container)) =>
|
||||
{
|
||||
let g = &mut host.hub.guests[gi];
|
||||
if let Some(c) = g.carried.take() {
|
||||
self.drop_guest_items(host, gi, vec![c]);
|
||||
@@ -1440,6 +1474,7 @@ impl Game<'_> {
|
||||
/// Per tick, for every guest: dig, use items, pick up drops, die.
|
||||
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
|
||||
self.lan_merchant_tick(host);
|
||||
self.lan_stations_tick(host);
|
||||
self.announce_guest_advancements(host);
|
||||
let conns: Vec<u32> = host
|
||||
.hub
|
||||
|
||||
@@ -55,6 +55,7 @@ fn load_player(menu: &mut Menu, g: &Guest) {
|
||||
menu.set_player_item(OFFHAND, g.offhand.clone());
|
||||
menu.selected = g.selected;
|
||||
menu.creative = g.creative();
|
||||
menu.levels = g.xp_level;
|
||||
menu.carried = g.carried.clone();
|
||||
}
|
||||
|
||||
@@ -83,27 +84,47 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec<ItemStack>) {
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn menu_env(&self) -> Env<'_> {
|
||||
pub(super) fn menu_env(&self) -> Env<'_> {
|
||||
Env {
|
||||
items: self.res.items(),
|
||||
recipes: self.res.recipes(),
|
||||
brewing: &self.res.stations().brewing,
|
||||
banners: &self.res.stations().banners,
|
||||
station_recipes: &self.res.stations().recipes,
|
||||
enchantments: &self.res.stations().enchantments,
|
||||
names: &self.pack.names,
|
||||
trade: None,
|
||||
maps: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `op` on the guest's menu with their inventory copied in and back.
|
||||
fn guest_menu_op<R>(
|
||||
pub(super) fn guest_menu_op<R>(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
gi: usize,
|
||||
menu: &mut Menu,
|
||||
op: impl FnOnce(&mut Menu, &Env) -> R,
|
||||
) -> R {
|
||||
let env = self.menu_env();
|
||||
// The cartography table reads and makes the host level's maps.
|
||||
let maps = (menu.kind() == Kind::Cartography).then(|| {
|
||||
let g = &host.hub.guests[gi];
|
||||
let held: Vec<ItemStack> = (0..menu.slot_count())
|
||||
.filter_map(|s| menu.slot(s).cloned())
|
||||
.chain(g.inventory.iter().flatten().cloned())
|
||||
.chain(g.carried.clone())
|
||||
.collect();
|
||||
self.level_maps(&held)
|
||||
});
|
||||
let env = Env {
|
||||
maps: maps.as_ref().map(|m| m as &dyn horizon_client::menu::Maps),
|
||||
..self.menu_env()
|
||||
};
|
||||
load_player(menu, &host.hub.guests[gi]);
|
||||
let result = op(menu, &env);
|
||||
if let Some(maps) = maps {
|
||||
self.register_made_maps(maps);
|
||||
}
|
||||
let dropped = std::mem::take(&mut menu.dropped);
|
||||
let equipped = std::mem::take(&mut menu.equipped);
|
||||
menu.drops.clear();
|
||||
@@ -201,8 +222,14 @@ impl Game<'_> {
|
||||
(Kind::Furnace(recipe), f.items.to_vec())
|
||||
}
|
||||
Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()),
|
||||
Some(BlockEntity::Crafter(c)) => (Kind::CrafterBlock, c.items.to_vec()),
|
||||
_ => return false,
|
||||
};
|
||||
// CrafterBlockEntity.containerData: the disabled slots, then triggered.
|
||||
let crafter_data = match self.world.block_entities.get(&pos) {
|
||||
Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)),
|
||||
_ => None,
|
||||
};
|
||||
if host.hub.guests[gi].spectator() {
|
||||
return true;
|
||||
}
|
||||
@@ -219,6 +246,13 @@ impl Game<'_> {
|
||||
for (k, s) in items.iter().enumerate() {
|
||||
menu.set_slot(env, k, s.clone());
|
||||
}
|
||||
// After the slots: setting a disabled slot (CrafterBlockEntity.setItem) enables it.
|
||||
if let Some((disabled, triggered)) = crafter_data {
|
||||
for (k, d) in disabled.iter().enumerate() {
|
||||
menu.data[k] = i32::from(*d);
|
||||
}
|
||||
menu.data[9] = i32::from(triggered);
|
||||
}
|
||||
let before: Vec<_> = (0..menu.slot_count())
|
||||
.map(|s| menu.slot(s).cloned())
|
||||
.collect();
|
||||
@@ -241,6 +275,13 @@ impl Game<'_> {
|
||||
b.items[k] = menu.slot(k).cloned();
|
||||
}
|
||||
}
|
||||
// CrafterBlockEntity.setItem: filling a disabled slot enables it.
|
||||
Some(BlockEntity::Crafter(c)) => {
|
||||
for k in 0..9 {
|
||||
c.items[k] = menu.slot(k).cloned();
|
||||
c.disabled[k] = menu.data[k] == 1;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu));
|
||||
@@ -248,6 +289,39 @@ impl Game<'_> {
|
||||
true
|
||||
}
|
||||
|
||||
/// `ServerGamePacketListenerImpl.handleContainerSlotStateChanged`: a
|
||||
/// guest's crafter slot toggle (`CrafterBlockEntity.setSlotState`) in
|
||||
/// their open crafter window.
|
||||
pub(super) fn lan_crafter_slot_state(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
window: i32,
|
||||
slot: i32,
|
||||
enabled: bool,
|
||||
) {
|
||||
let Some(pos) = host
|
||||
.hub
|
||||
.guest(conn)
|
||||
.filter(|g| !g.spectator())
|
||||
.and_then(|g| g.menu.as_ref())
|
||||
.filter(|m| window != 0 && m.window == window)
|
||||
.and_then(|m| match m.slots {
|
||||
Slots::Block(pos) => Some(pos),
|
||||
_ => None,
|
||||
})
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let (Some(BlockEntity::Crafter(c)), Ok(slot)) = (
|
||||
self.world.block_entities.get_mut(&pos),
|
||||
usize::try_from(slot),
|
||||
) {
|
||||
c.set_slot_state(slot, enabled);
|
||||
self.world.modified.insert((pos.0 >> 4, pos.2 >> 4));
|
||||
}
|
||||
}
|
||||
|
||||
/// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe
|
||||
/// book places a known recipe in their inventory grid or crafting table
|
||||
/// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items
|
||||
@@ -331,6 +405,7 @@ impl Game<'_> {
|
||||
/// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`).
|
||||
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) {
|
||||
self.lan_crafting_closed(host, conn, None);
|
||||
self.lan_station_closed(host, conn, None);
|
||||
// The container it replaces loses its opener.
|
||||
self.guest_container_closed(host, conn);
|
||||
let title = horizon_protocol::text::translatable("container.crafting", &[]);
|
||||
@@ -430,22 +505,35 @@ impl Game<'_> {
|
||||
None => return false,
|
||||
}
|
||||
};
|
||||
if grid.is_empty() {
|
||||
return true;
|
||||
if !grid.is_empty() {
|
||||
self.lan_place_back(host, gi, grid);
|
||||
}
|
||||
let mut menu = Menu::new(Kind::Inventory);
|
||||
self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid));
|
||||
true
|
||||
}
|
||||
|
||||
/// A guest left: what their crafting grids held goes back into their
|
||||
/// `Inventory.placeItemBackInInventory` of `stacks` for guest `gi`, what
|
||||
/// doesn't fit dropped (`clearContainer`).
|
||||
pub(super) fn lan_place_back(&mut self, host: &mut LanHost, gi: usize, stacks: Vec<ItemStack>) {
|
||||
let mut menu = Menu::new(Kind::Inventory);
|
||||
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
|
||||
place_back(menu, env, stacks)
|
||||
});
|
||||
}
|
||||
|
||||
/// A guest left: what their crafting grids and workstation held goes back into their
|
||||
/// inventory before it is saved (dropped where they stood if full).
|
||||
pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) {
|
||||
let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table);
|
||||
let play = host.play.remove(&g.conn);
|
||||
let mut grid: Vec<ItemStack> = g.craft_grid.iter_mut().filter_map(Option::take).collect();
|
||||
g.craft_result = None;
|
||||
if let Some((_, _, menu)) = table {
|
||||
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
|
||||
if let Some(play) = play {
|
||||
if let Some((_, _, menu)) = play.crafting.table {
|
||||
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
|
||||
}
|
||||
// A workstation's inputs too.
|
||||
if let Some(station) = &play.station {
|
||||
grid.extend(super::lan_stations::station_inputs(station));
|
||||
}
|
||||
}
|
||||
if grid.is_empty() {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,672 @@
|
||||
//! Workstation menus for LAN guests: the screen a guest's use opens runs on
|
||||
//! the host's menu engine (`horizon_client::menu`), the one single player
|
||||
//! uses, with vanilla's packets: OpenScreen with the station's `MenuType`,
|
||||
//! container clicks, `ServerboundContainerButtonClickPacket`, the content and
|
||||
//! data slot sync after each (`broadcastChanges`), and the inputs back into
|
||||
//! the inventory when the menu closes (`AbstractContainerMenu.clearContainer`).
|
||||
use super::{
|
||||
Game,
|
||||
lan::LanHost,
|
||||
lan_crafting::input,
|
||||
stations::{Kind as StationKind, Station},
|
||||
};
|
||||
use horizon_client::{
|
||||
containers::BlockEntity,
|
||||
items::ItemStack,
|
||||
menu::{Kind, Menu},
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
|
||||
/// A guest's open workstation menu.
|
||||
pub(super) struct GuestStation {
|
||||
window: i32,
|
||||
state: i32,
|
||||
kind: StationKind,
|
||||
pos: [i32; 3],
|
||||
menu: Box<Menu>,
|
||||
/// The data slots the client was last sent.
|
||||
sent_data: Vec<i32>,
|
||||
/// The game time of the menu's last sound (`lastSoundTime`).
|
||||
last_sound: u64,
|
||||
}
|
||||
|
||||
/// A guest's open lectern: `LecternMenu` over the block entity, made on the
|
||||
/// menu engine for each click (`Game::lectern_menu`).
|
||||
pub(super) struct GuestLectern {
|
||||
window: i32,
|
||||
state: i32,
|
||||
key: (i32, i32, i32),
|
||||
/// The book and page the client was last sent (`broadcastChanges`).
|
||||
sent: Option<(Option<ItemStack>, i32)>,
|
||||
}
|
||||
|
||||
/// The `MenuType`, the engine's menu and the input slots
|
||||
/// (`clearContainer`'s container) of a station a guest can use.
|
||||
fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range<usize>)> {
|
||||
Some(match kind {
|
||||
StationKind::Loom => ("minecraft:loom", Kind::Loom, 0..3),
|
||||
StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1),
|
||||
StationKind::Grindstone => ("minecraft:grindstone", Kind::Grindstone, 0..2),
|
||||
StationKind::Anvil => ("minecraft:anvil", Kind::Anvil, 0..2),
|
||||
StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3),
|
||||
StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2),
|
||||
StationKind::Beacon => ("minecraft:beacon", Kind::Beacon, 0..1),
|
||||
StationKind::Cartography => ("minecraft:cartography_table", Kind::Cartography, 0..2),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// A workstation a guest's use opened (`ServerPlayer.openMenu`); false
|
||||
/// when guests can't use that one yet.
|
||||
pub(super) fn lan_open_station(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
station: &Station,
|
||||
) -> bool {
|
||||
let Some((menu_type, kind, _)) = menu_of(station.kind) else {
|
||||
return false;
|
||||
};
|
||||
self.lan_station_closed(host, conn, None);
|
||||
self.lan_crafting_closed(host, conn, None);
|
||||
// The container it replaces loses its opener.
|
||||
self.guest_container_closed(host, conn);
|
||||
let title = horizon_protocol::text::translatable(station.kind.title_key(), &[]);
|
||||
let Some(window) = host.hub.open_window(conn, menu_type, title) else {
|
||||
return true;
|
||||
};
|
||||
let mut menu = Box::new(Menu::new(kind));
|
||||
if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn)
|
||||
&& kind == Kind::Enchanting
|
||||
{
|
||||
// Player.enchantmentSeed, made when first needed.
|
||||
if g.xp_seed == 0 {
|
||||
g.xp_seed = self.world.random.next_int();
|
||||
}
|
||||
menu.data[3] = g.xp_seed;
|
||||
}
|
||||
if kind == Kind::Beacon {
|
||||
menu.data = self.beacon_data(host, station.pos).to_vec();
|
||||
}
|
||||
host.play.entry(conn).or_default().station = Some(GuestStation {
|
||||
window,
|
||||
state: 0,
|
||||
kind: station.kind,
|
||||
pos: station.pos,
|
||||
menu,
|
||||
sent_data: Vec::new(),
|
||||
last_sound: 0,
|
||||
});
|
||||
self.lan_send_station(host, conn);
|
||||
true
|
||||
}
|
||||
|
||||
/// Runs `op` on the guest's open station (window `window`, any when
|
||||
/// None) with their inventory in it, then sends what changed. False when
|
||||
/// no such window is open.
|
||||
fn lan_station_op(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
window: Option<i32>,
|
||||
op: impl FnOnce(&mut Menu, &horizon_client::menu::Env),
|
||||
) -> bool {
|
||||
let Some(mut gs) = host
|
||||
.play
|
||||
.get_mut(&conn)
|
||||
.and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w)))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
|
||||
&& !host.hub.guests[gi].spectator()
|
||||
{
|
||||
self.guest_menu_op(host, gi, &mut gs.menu, op);
|
||||
self.lan_station_sounds(&mut gs);
|
||||
if let Some(amount) = gs.menu.ground.take() {
|
||||
self.grindstone_taken(gs.pos, amount);
|
||||
}
|
||||
self.lan_station_combined(host, conn, &mut gs);
|
||||
if let Some(button) = gs.menu.enchant_button.take() {
|
||||
self.lan_enchant(host, gi, &mut gs, button);
|
||||
}
|
||||
if std::mem::take(&mut gs.menu.enchant_changed) {
|
||||
self.lan_enchant_offers(host, gi, &mut gs);
|
||||
}
|
||||
}
|
||||
host.play.entry(conn).or_default().station = Some(gs);
|
||||
self.lan_send_station(host, conn);
|
||||
true
|
||||
}
|
||||
|
||||
/// `LecternBlock.openScreen` for a guest: `minecraft:lectern` over the
|
||||
/// block entity, with its book and page.
|
||||
pub(super) fn lan_open_lectern(&mut self, host: &mut LanHost, conn: u32, key: (i32, i32, i32)) {
|
||||
self.lan_station_closed(host, conn, None);
|
||||
self.lan_crafting_closed(host, conn, None);
|
||||
self.guest_container_closed(host, conn);
|
||||
let title = horizon_protocol::text::translatable("container.lectern", &[]);
|
||||
let Some(window) = host.hub.open_window(conn, "minecraft:lectern", title) else {
|
||||
return;
|
||||
};
|
||||
host.play.entry(conn).or_default().lectern = Some(GuestLectern {
|
||||
window,
|
||||
state: 0,
|
||||
key,
|
||||
sent: None,
|
||||
});
|
||||
self.lan_send_lectern(host, conn, true);
|
||||
}
|
||||
|
||||
/// The lectern's book and page for the client: everything (`all`), or
|
||||
/// what changed since it was last sent.
|
||||
fn lan_send_lectern(&mut self, host: &mut LanHost, conn: u32, all: bool) {
|
||||
let Some(gl) = host.play.get_mut(&conn).and_then(|p| p.lectern.as_mut()) else {
|
||||
return;
|
||||
};
|
||||
let (book, page) = match self.world.block_entities.get(&gl.key) {
|
||||
Some(BlockEntity::Lectern(l)) => (l.book.clone(), l.page),
|
||||
_ => (None, 0),
|
||||
};
|
||||
let now = Some((book.clone(), page));
|
||||
if !all && gl.sent == now {
|
||||
return;
|
||||
}
|
||||
let page_changed = gl.sent.as_ref().is_none_or(|(_, p)| *p != page);
|
||||
gl.sent = now;
|
||||
gl.state = (gl.state + 1) & 0x7FFF;
|
||||
let (window, state) = (gl.window, gl.state);
|
||||
let carried = host
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.find(|g| g.conn == conn)
|
||||
.and_then(|g| g.carried.clone());
|
||||
let content = C::ContainerSetContent(play::ContainerSetContent {
|
||||
container: window,
|
||||
state,
|
||||
items: vec![host.hub.stack(&book)],
|
||||
carried: host.hub.stack(&carried),
|
||||
});
|
||||
host.hub.send_to(conn, &content);
|
||||
if all || page_changed {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::ContainerSetData(play::ContainerSetData {
|
||||
container: window,
|
||||
id: 0,
|
||||
value: page as i16,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `op` on the guest's lectern menu (window `window`) with their
|
||||
/// inventory, the block entity takes the book and page back, and the
|
||||
/// client gets what changed. False when no such window is open.
|
||||
fn lan_lectern_op(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
window: i32,
|
||||
op: impl FnOnce(&mut Menu, &horizon_client::menu::Env),
|
||||
) -> bool {
|
||||
let Some(key) = host
|
||||
.play
|
||||
.get(&conn)
|
||||
.and_then(|p| p.lectern.as_ref())
|
||||
.filter(|l| l.window == window)
|
||||
.map(|l| l.key)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
|
||||
&& !host.hub.guests[gi].spectator()
|
||||
&& let Some(mut menu) = self.lectern_menu(key)
|
||||
{
|
||||
// Player.mayBuild: survival and creative.
|
||||
let may_build = matches!(host.hub.guests[gi].game_mode, 0 | 1);
|
||||
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
|
||||
menu.may_build = may_build;
|
||||
op(menu, env);
|
||||
});
|
||||
self.lectern_menu_done(key, &menu);
|
||||
}
|
||||
self.lan_send_lectern(host, conn, true);
|
||||
true
|
||||
}
|
||||
|
||||
/// A click on the guest's lectern window; false for other windows.
|
||||
pub(super) fn lan_lectern_click(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
p: &play::ContainerClick,
|
||||
) -> bool {
|
||||
self.lan_lectern_op(host, conn, p.container, |menu, env| {
|
||||
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
|
||||
})
|
||||
}
|
||||
|
||||
/// The rest of a taken anvil or smithing result's `onTake`: the guest
|
||||
/// pays the levels, the anvil wears (level event 1030 or 1029), the
|
||||
/// smithing table sounds (1044).
|
||||
fn lan_station_combined(&mut self, host: &mut LanHost, conn: u32, gs: &mut GuestStation) {
|
||||
let change = std::mem::take(&mut gs.menu.level_change);
|
||||
if change != 0 {
|
||||
self.as_guest(host, conn, |g| g.give_levels(change));
|
||||
}
|
||||
if !std::mem::take(&mut gs.menu.combined) {
|
||||
return;
|
||||
}
|
||||
if gs.kind == StationKind::Smithing {
|
||||
self.level_event_at(1044, gs.pos, 0);
|
||||
} else {
|
||||
let creative = gs.menu.creative;
|
||||
// A broken anvil closes the menu on the next stillValid check.
|
||||
self.anvil_used(gs.pos, creative);
|
||||
}
|
||||
}
|
||||
|
||||
/// `EnchantmentMenu.slotsChanged` with a level: the costs and clues for
|
||||
/// the guest's seed and the bookshelves around the table.
|
||||
fn lan_enchant_offers(&mut self, host: &LanHost, gi: usize, gs: &mut GuestStation) {
|
||||
let seed = host.hub.guests[gi].xp_seed;
|
||||
let bookcases = self.count_bookshelves(gs.pos);
|
||||
let offers = horizon_client::stations::enchant_offers(
|
||||
&self.res.stations().enchantments,
|
||||
self.res.items(),
|
||||
seed,
|
||||
bookcases,
|
||||
gs.menu.slot(0),
|
||||
);
|
||||
for i in 0..3 {
|
||||
gs.menu.data[i] = offers.costs[i];
|
||||
let clue = offers.clues[i].as_ref();
|
||||
gs.menu.data[4 + i] = clue
|
||||
.and_then(|(e, _)| host.hub.registry_id("minecraft:enchantment", e))
|
||||
.unwrap_or(-1);
|
||||
gs.menu.data[7 + i] = clue.map_or(-1, |(_, l)| *l as i32);
|
||||
}
|
||||
gs.menu.data[3] = seed;
|
||||
}
|
||||
|
||||
/// `EnchantmentMenu.clickMenuButton`'s `access.execute`: the item gets
|
||||
/// the offer's enchantments, the guest pays its levels and lapis and
|
||||
/// gets a new seed, the table sounds, and the offers are made again.
|
||||
fn lan_enchant(&mut self, host: &mut LanHost, gi: usize, gs: &mut GuestStation, button: usize) {
|
||||
let Some(item) = gs.menu.slot(0).cloned() else {
|
||||
return;
|
||||
};
|
||||
let g = &host.hub.guests[gi];
|
||||
let (seed, creative, conn) = (g.xp_seed, g.creative(), g.conn);
|
||||
let Some(enchanted) = horizon_client::stations::apply_enchantment(
|
||||
&self.res.stations().enchantments,
|
||||
self.res.items(),
|
||||
seed,
|
||||
button,
|
||||
gs.menu.data[button],
|
||||
&item,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let need = button as i32 + 1;
|
||||
// Player.onEnchantmentPerformed, and EnchantmentMenu's awardStat(ENCHANT_ITEM).
|
||||
self.as_guest(host, conn, |game| {
|
||||
game.give_levels(-need);
|
||||
game.stats.custom("enchant_item", 1);
|
||||
});
|
||||
host.hub.guests[gi].xp_seed = self.world.random.next_int();
|
||||
let env = self.menu_env();
|
||||
let lapis = gs.menu.slot(1).cloned().filter(|_| !creative).map(|mut l| {
|
||||
l.count = l.count.saturating_sub(need as u32);
|
||||
l
|
||||
});
|
||||
gs.menu.set_slot(&env, 0, Some(enchanted));
|
||||
if !creative {
|
||||
gs.menu.set_slot(&env, 1, lapis.filter(|l| l.count > 0));
|
||||
}
|
||||
gs.menu.enchant_changed = false;
|
||||
self.lan_enchant_offers(host, gi, gs);
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
let at = gs.pos.map(|v| f64::from(v) + 0.5);
|
||||
self.audio.play(
|
||||
"minecraft:block.enchantment_table.use",
|
||||
Some(at),
|
||||
1.0,
|
||||
pitch,
|
||||
);
|
||||
}
|
||||
|
||||
/// `ServerGamePacketListenerImpl.handleRenameItem`: the guest's anvil
|
||||
/// takes the name (`AnvilMenu.setItemName`).
|
||||
pub(super) fn lan_station_rename(&mut self, host: &mut LanHost, conn: u32, name: &str) {
|
||||
let anvil = host
|
||||
.play
|
||||
.get(&conn)
|
||||
.and_then(|p| p.station.as_ref())
|
||||
.is_some_and(|s| s.kind == StationKind::Anvil);
|
||||
if anvil {
|
||||
self.lan_station_op(host, conn, None, |menu, env| {
|
||||
menu.rename(env, name);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The sounds the menu played, at the station (heard by everyone around,
|
||||
/// as `level.playSound(null, pos, ...)`), once per tick.
|
||||
fn lan_station_sounds(&mut self, gs: &mut GuestStation) {
|
||||
let sounds = std::mem::take(&mut gs.menu.sounds);
|
||||
if sounds.is_empty() || gs.last_sound == self.ticks {
|
||||
return;
|
||||
}
|
||||
gs.last_sound = self.ticks;
|
||||
let at = gs.pos.map(|v| f64::from(v) + 0.5);
|
||||
for sound in sounds {
|
||||
self.audio.play(sound, Some(at), 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on the guest's station window; false for other windows.
|
||||
pub(super) fn lan_station_click(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
p: &play::ContainerClick,
|
||||
) -> bool {
|
||||
self.lan_station_op(host, conn, Some(p.container), |menu, env| {
|
||||
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
|
||||
})
|
||||
}
|
||||
|
||||
/// `ServerGamePacketListenerImpl.handleContainerButtonClick`:
|
||||
/// `clickMenuButton`, then `broadcastChanges` when the menu took it.
|
||||
pub(super) fn lan_station_button(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
window: i32,
|
||||
id: i32,
|
||||
) {
|
||||
// LecternMenu's page buttons and Take Book.
|
||||
if self.lan_lectern_op(host, conn, window, |menu, env| {
|
||||
menu.button(env, id);
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
self.lan_station_op(host, conn, Some(window), |menu, env| {
|
||||
menu.button(env, id);
|
||||
});
|
||||
}
|
||||
|
||||
/// The whole station menu and its changed data slots for the client
|
||||
/// (`sendAllDataToRemote` / `broadcastChanges`).
|
||||
fn lan_send_station(&mut self, host: &mut LanHost, conn: u32) {
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
return;
|
||||
};
|
||||
let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) else {
|
||||
return;
|
||||
};
|
||||
gs.state = (gs.state + 1) & 0x7FFF;
|
||||
let own = gs.menu.slot_count() - 36;
|
||||
let mut items: Vec<Option<ItemStack>> =
|
||||
(0..own).map(|s| gs.menu.slot(s).cloned()).collect();
|
||||
let g = &host.hub.guests[gi];
|
||||
items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone()));
|
||||
let carried = g.carried.clone();
|
||||
let packet = C::ContainerSetContent(play::ContainerSetContent {
|
||||
container: gs.window,
|
||||
state: gs.state,
|
||||
items: items.iter().map(|s| host.hub.stack(s)).collect(),
|
||||
carried: host.hub.stack(&carried),
|
||||
});
|
||||
gs.sent_data.resize(gs.menu.data.len(), i32::MIN);
|
||||
let mut data = Vec::new();
|
||||
for (k, &v) in gs.menu.data.iter().enumerate() {
|
||||
if gs.sent_data[k] != v {
|
||||
gs.sent_data[k] = v;
|
||||
data.push(C::ContainerSetData(play::ContainerSetData {
|
||||
container: gs.window,
|
||||
id: k as i16,
|
||||
value: v as i16,
|
||||
}));
|
||||
}
|
||||
}
|
||||
host.hub.send_to(conn, &packet);
|
||||
for packet in data {
|
||||
host.hub.send_to(conn, &packet);
|
||||
}
|
||||
}
|
||||
|
||||
/// `AbstractContainerMenu.removed` of the guest's station (`window`;
|
||||
/// None closes it whichever it is): the carried stack and the inputs go
|
||||
/// back to the inventory, what doesn't fit is dropped. False when no such
|
||||
/// window is open.
|
||||
pub(super) fn lan_station_closed(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
window: Option<i32>,
|
||||
) -> bool {
|
||||
// A lectern's menu keeps nothing of its own (the book is the block entity's).
|
||||
let lectern = host
|
||||
.play
|
||||
.get_mut(&conn)
|
||||
.and_then(|p| p.lectern.take_if(|l| window.is_none_or(|w| l.window == w)));
|
||||
if lectern.is_some() {
|
||||
// AbstractContainerMenu.removed: the carried stack goes back.
|
||||
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
|
||||
&& let Some(carried) = host.hub.guests[gi].carried.take()
|
||||
{
|
||||
self.lan_place_back(host, gi, vec![carried]);
|
||||
}
|
||||
if window.is_some() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let Some(gs) = host
|
||||
.play
|
||||
.get_mut(&conn)
|
||||
.and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w)))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
|
||||
return true;
|
||||
};
|
||||
// AbstractContainerMenu.removed: the carried stack first, then the inputs.
|
||||
let mut back: Vec<ItemStack> = host.hub.guests[gi].carried.take().into_iter().collect();
|
||||
let inputs = station_inputs(&gs);
|
||||
if gs.kind == StationKind::Beacon {
|
||||
// BeaconMenu.removed drops the payment (player.drop).
|
||||
if !back.is_empty() {
|
||||
self.lan_place_back(host, gi, std::mem::take(&mut back));
|
||||
}
|
||||
self.drop_guest_items(host, gi, inputs);
|
||||
} else {
|
||||
back.extend(inputs);
|
||||
}
|
||||
if !back.is_empty() {
|
||||
self.lan_place_back(host, gi, back);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `BeaconBlockEntity.dataAccess`: the pyramid's levels and the powers
|
||||
/// (`BeaconMenu.encodeEffect`: the `mob_effect` id + 1, 0 for none).
|
||||
fn beacon_data(&self, host: &LanHost, pos: [i32; 3]) -> [i32; 3] {
|
||||
let Some(BlockEntity::Beacon(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
|
||||
else {
|
||||
return [0; 3];
|
||||
};
|
||||
let encode = |e: &Option<String>| {
|
||||
e.as_deref()
|
||||
.and_then(|n| host.hub.registry_id("minecraft:mob_effect", n))
|
||||
.map_or(0, |id| id + 1)
|
||||
};
|
||||
[b.levels, encode(&b.primary), encode(&b.secondary)]
|
||||
}
|
||||
|
||||
/// `ServerGamePacketListenerImpl.handleSetBeaconPacket`: the guest's
|
||||
/// beacon menu takes the powers (`BeaconMenu.updateEffects`), and they
|
||||
/// become the block entity's (`dataAccess.set`: the power_select sound
|
||||
/// while the beam is up).
|
||||
pub(super) fn lan_station_beacon(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
conn: u32,
|
||||
primary: Option<i32>,
|
||||
secondary: Option<i32>,
|
||||
) {
|
||||
let Some(pos) = host
|
||||
.play
|
||||
.get(&conn)
|
||||
.and_then(|p| p.station.as_ref())
|
||||
.filter(|s| s.kind == StationKind::Beacon)
|
||||
.map(|s| s.pos)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
// An id the registry doesn't have fails the packet's codec.
|
||||
let mut powers: [Option<(i32, String)>; 2] = [None, None];
|
||||
for (k, id) in [primary, secondary].into_iter().enumerate() {
|
||||
if let Some(id) = id {
|
||||
let Some(name) = host.hub.registry_name("minecraft:mob_effect", id) else {
|
||||
return;
|
||||
};
|
||||
powers[k] = Some((id, name.to_owned()));
|
||||
}
|
||||
}
|
||||
let data = self.beacon_data(host, pos);
|
||||
let mut updated = false;
|
||||
self.lan_station_op(host, conn, None, |menu, env| {
|
||||
menu.data.copy_from_slice(&data);
|
||||
let power = |k: usize| powers[k].as_ref().map(|(id, n)| (*id, n.as_str()));
|
||||
updated = menu.beacon_update(env, power(0), power(1));
|
||||
});
|
||||
if !updated {
|
||||
return;
|
||||
}
|
||||
let [primary, secondary] = powers.map(|p| p.map(|(_, n)| n));
|
||||
let mut select_sound = false;
|
||||
if let Some(BlockEntity::Beacon(b)) =
|
||||
self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2]))
|
||||
{
|
||||
b.primary = primary;
|
||||
b.secondary = secondary;
|
||||
select_sound = !b.sections.is_empty();
|
||||
}
|
||||
if select_sound {
|
||||
self.beacon_sound(pos, "minecraft:block.beacon.power_select");
|
||||
}
|
||||
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
|
||||
}
|
||||
|
||||
/// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its
|
||||
/// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`).
|
||||
pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) {
|
||||
self.lan_lecterns_tick(host);
|
||||
let conns: Vec<u32> = host
|
||||
.play
|
||||
.iter()
|
||||
.filter(|(_, p)| p.station.is_some())
|
||||
.map(|(c, _)| *c)
|
||||
.collect();
|
||||
for conn in conns {
|
||||
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
|
||||
continue;
|
||||
};
|
||||
if !host.hub.here(g) {
|
||||
continue;
|
||||
}
|
||||
let Some(gs) = host.play.get(&conn).and_then(|p| p.station.as_ref()) else {
|
||||
continue;
|
||||
};
|
||||
let [x, y, z] = gs.pos;
|
||||
let name = &self.res.facts().get(self.world.block(x, y, z)).name;
|
||||
let block = StationKind::from_block(name) == Some(gs.kind);
|
||||
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
|
||||
// The block interaction range (4.5, creative 5) and the buffer.
|
||||
let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0;
|
||||
let near = (0..3)
|
||||
.map(|k| {
|
||||
let lo = f64::from(gs.pos[k]);
|
||||
(lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2)
|
||||
})
|
||||
.sum::<f64>()
|
||||
< reach * reach;
|
||||
if !(block && near) {
|
||||
let window = gs.window;
|
||||
self.lan_station_closed(host, conn, Some(window));
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::ContainerClose(play::ContainerClose { container: window }),
|
||||
);
|
||||
} else if gs.kind == StationKind::Beacon {
|
||||
// The beacon's data slots follow its block entity.
|
||||
let data = self.beacon_data(host, gs.pos);
|
||||
if let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut())
|
||||
&& gs.menu.data[..] != data[..]
|
||||
{
|
||||
gs.menu.data.copy_from_slice(&data);
|
||||
self.lan_send_station(host, conn);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// The guests' lecterns each tick: `stillValid` (the block entity, its
|
||||
/// book, the reach) closes them, and `broadcastChanges` sends a book or
|
||||
/// page another player changed.
|
||||
fn lan_lecterns_tick(&mut self, host: &mut LanHost) {
|
||||
let open: Vec<(u32, i32, (i32, i32, i32))> = host
|
||||
.play
|
||||
.iter()
|
||||
.filter_map(|(c, p)| p.lectern.as_ref().map(|l| (*c, l.window, l.key)))
|
||||
.collect();
|
||||
for (conn, window, key) in open {
|
||||
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
|
||||
continue;
|
||||
};
|
||||
if !host.hub.here(g) {
|
||||
continue;
|
||||
}
|
||||
let has_book = matches!(
|
||||
self.world.block_entities.get(&key),
|
||||
Some(BlockEntity::Lectern(l)) if l.book.is_some()
|
||||
);
|
||||
// Container.stillValidBlockEntity: the interaction range and its buffer.
|
||||
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
|
||||
let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0;
|
||||
let pos = [key.0, key.1, key.2];
|
||||
let near = (0..3)
|
||||
.map(|k| {
|
||||
let lo = f64::from(pos[k]);
|
||||
(lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2)
|
||||
})
|
||||
.sum::<f64>()
|
||||
< reach * reach;
|
||||
if has_book && near {
|
||||
self.lan_send_lectern(host, conn, false);
|
||||
} else {
|
||||
self.lan_station_closed(host, conn, Some(window));
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::ContainerClose(play::ContainerClose { container: window }),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `clearContainer` gives back from a station's menu.
|
||||
pub(super) fn station_inputs(gs: &GuestStation) -> Vec<ItemStack> {
|
||||
menu_of(gs.kind)
|
||||
.map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -55,8 +55,9 @@ impl Game<'_> {
|
||||
state.session.update_special_prices();
|
||||
}
|
||||
let title = self.merchant_display_name(&state);
|
||||
// The container the trading screen replaces loses its opener.
|
||||
// The container or workstation the trading screen replaces is closed.
|
||||
self.guest_container_closed(host, conn);
|
||||
self.lan_station_closed(host, conn, None);
|
||||
let Some(window) = host.hub.open_merchant_window(conn, title) else {
|
||||
self.merchant_closed(&mut state);
|
||||
return;
|
||||
@@ -254,7 +255,11 @@ impl Game<'_> {
|
||||
recipes: self.res.recipes(),
|
||||
brewing: &self.res.stations().brewing,
|
||||
banners: &self.res.stations().banners,
|
||||
station_recipes: &self.res.stations().recipes,
|
||||
enchantments: &self.res.stations().enchantments,
|
||||
names: &self.pack.names,
|
||||
trade: Some(&trade_env),
|
||||
maps: None,
|
||||
};
|
||||
let mut menu = Menu::new(Kind::Merchant);
|
||||
{
|
||||
@@ -393,8 +398,8 @@ impl Game<'_> {
|
||||
});
|
||||
}
|
||||
}
|
||||
/// Takes a station a guest's action opened: a trading screen goes to the
|
||||
/// guest; other stations are not shown to guests yet.
|
||||
/// Takes a station a guest's action opened: a trading screen or a
|
||||
/// workstation menu goes to the guest (game/lan_stations.rs).
|
||||
pub(super) fn lan_station_opened(
|
||||
&mut self,
|
||||
host: &mut LanHost,
|
||||
@@ -406,6 +411,8 @@ impl Game<'_> {
|
||||
&& let Some(m) = station.merchant.take()
|
||||
{
|
||||
self.lan_open_merchant(host, conn, *m);
|
||||
return;
|
||||
}
|
||||
self.lan_open_station(host, conn, &station);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,8 +68,9 @@ impl Game<'_> {
|
||||
}
|
||||
l.last_inputs = inputs;
|
||||
}
|
||||
/// A sound the loom menu played: the result's once per tick.
|
||||
pub(super) fn loom_sound(&mut self, sound: &str) {
|
||||
/// A sound the loom or stonecutter menu played: the result's once per
|
||||
/// tick (`lastSoundTime`).
|
||||
pub(super) fn station_sound(&mut self, sound: &str) {
|
||||
let ticks = self.ticks;
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
@@ -98,6 +99,7 @@ impl Game<'_> {
|
||||
if taken {
|
||||
self.audio
|
||||
.play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0);
|
||||
self.remote_station_button(index as i32);
|
||||
}
|
||||
taken
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use horizon_client::{
|
||||
containers::Crafter,
|
||||
hud::{HudBatch, rgba},
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Serverbound as S};
|
||||
use serde_json::Value;
|
||||
|
||||
/// `CrafterBlock`'s crafting animation length.
|
||||
@@ -323,6 +324,15 @@ impl Game<'_> {
|
||||
menu.set_slot_state(i, enabled);
|
||||
Some(true)
|
||||
});
|
||||
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.clone()) {
|
||||
self.send(S::ContainerSlotStateChanged(
|
||||
play::ContainerSlotStateChanged {
|
||||
slot: i as i32,
|
||||
container,
|
||||
enabled,
|
||||
},
|
||||
));
|
||||
}
|
||||
let pitch = if enabled { 1.0 } else { 0.75 };
|
||||
self.audio
|
||||
.play("minecraft:ui.button.click", None, 0.4, pitch);
|
||||
|
||||
@@ -279,7 +279,11 @@ impl Game<'_> {
|
||||
recipes: self.res.recipes(),
|
||||
brewing: &self.res.stations().brewing,
|
||||
banners: &self.res.stations().banners,
|
||||
station_recipes: &self.res.stations().recipes,
|
||||
enchantments: &self.res.stations().enchantments,
|
||||
names: &self.pack.names,
|
||||
trade: None,
|
||||
maps: None,
|
||||
};
|
||||
for i in 0..36 {
|
||||
menu.set_player_item(i, self.inventory[i].clone());
|
||||
|
||||
@@ -116,9 +116,9 @@ pub(super) struct Remote {
|
||||
/// only replace the remembered state; then the block takes it.
|
||||
predictions: HashMap<[i32; 3], (i32, i32)>,
|
||||
/// Open container: (window id, menu name).
|
||||
menu: Option<(i32, String)>,
|
||||
pub(super) menu: Option<(i32, String)>,
|
||||
/// The open menu's title as the server named it.
|
||||
menu_title: Option<String>,
|
||||
pub(super) menu_title: Option<String>,
|
||||
state_id: i32,
|
||||
use_target: Option<[i32; 3]>,
|
||||
entities: HashMap<i32, Tracked>,
|
||||
@@ -471,8 +471,15 @@ impl Game<'_> {
|
||||
.unwrap_or("minecraft:air"),
|
||||
)
|
||||
}
|
||||
/// The server's network id of a mob effect (`brewing::EFFECTS` id).
|
||||
pub(super) fn remote_effect_network_id(&self, effect: &str) -> Option<i32> {
|
||||
let r = self.remote.as_ref()?;
|
||||
r.builtin
|
||||
.get("minecraft:mob_effect")?
|
||||
.id(&format!("minecraft:{effect}"))
|
||||
}
|
||||
/// A mob effect's network id as the effect (`brewing::EFFECTS` id).
|
||||
fn remote_effect_id(&self, effect: i32) -> Option<&'static str> {
|
||||
pub(super) fn remote_effect_id(&self, effect: i32) -> Option<&'static str> {
|
||||
let r = self.remote.as_ref()?;
|
||||
let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?;
|
||||
horizon_client::brewing::effect(name).map(|d| d.id)
|
||||
@@ -518,6 +525,54 @@ impl Game<'_> {
|
||||
if let Some(Component::Int(id)) = s.component(component::MAP_ID) {
|
||||
out.data_mut().map_id = Some(*id);
|
||||
}
|
||||
if let Some(Component::Int(cost)) = s.component(component::REPAIR_COST) {
|
||||
out.data_mut().repair_cost = (*cost).max(0) as u32;
|
||||
}
|
||||
if let Some(Component::Int(mode)) = s.component(component::MAP_POST_PROCESSING) {
|
||||
out.data_mut().map_post_processing = Some((*mode).clamp(0, 1) as u8);
|
||||
}
|
||||
if let Some(Component::WritableBook(pages)) = s.component(component::WRITABLE_BOOK_CONTENT)
|
||||
{
|
||||
out.data_mut().writable_pages = pages.clone();
|
||||
}
|
||||
if let Some(Component::WrittenBook(b)) = s.component(component::WRITTEN_BOOK_CONTENT) {
|
||||
let lang = self
|
||||
.remote
|
||||
.as_ref()
|
||||
.map(|r| r.lang.clone())
|
||||
.unwrap_or_default();
|
||||
out.data_mut().written = Some(horizon_client::item_data::WrittenBook {
|
||||
title: b.title.clone(),
|
||||
author: b.author.clone(),
|
||||
generation: b.generation.clamp(0, 3) as u8,
|
||||
pages: b.pages.iter().map(|p| plain(p, &lang)).collect(),
|
||||
});
|
||||
}
|
||||
if let Some(Component::Text(name)) = s.component(component::CUSTOM_NAME) {
|
||||
let lang = self
|
||||
.remote
|
||||
.as_ref()
|
||||
.map(|r| r.lang.clone())
|
||||
.unwrap_or_default();
|
||||
out.data_mut().custom_name = Some(plain(name, &lang));
|
||||
}
|
||||
// The enchantments by the server's registry ids.
|
||||
let levels = |list: &[(i32, i32)]| -> Vec<(Arc<str>, u32)> {
|
||||
let names = self.remote.as_ref().map(|r| &r.registries);
|
||||
list.iter()
|
||||
.filter_map(|(id, level)| {
|
||||
let name = names?.name("minecraft:enchantment", *id)?;
|
||||
Some((Arc::from(name), (*level).max(0) as u32))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) {
|
||||
out.data_mut().enchantments = levels(list);
|
||||
}
|
||||
if let Some(Component::Enchantments(list)) = s.component(component::STORED_ENCHANTMENTS) {
|
||||
out.data_mut().stored_enchantments = levels(list);
|
||||
}
|
||||
out.tidy();
|
||||
Some(out)
|
||||
}
|
||||
fn to_network(&self, s: &Option<ItemStack>) -> Option<Stack> {
|
||||
@@ -1294,9 +1349,39 @@ impl Game<'_> {
|
||||
"minecraft:hopper" => slots(5),
|
||||
"minecraft:generic_3x3" => slots(9),
|
||||
"minecraft:brewing_stand" => slots(5),
|
||||
_ => None,
|
||||
// CrafterMenu: the grid, the inventory, then the result (the
|
||||
// client's own).
|
||||
"minecraft:crafter_3x3" => slots(9),
|
||||
// A workstation: its inputs, its result, then the inventory.
|
||||
m => {
|
||||
let kind = Self::remote_station_kind(m)?;
|
||||
let inputs = kind.inputs();
|
||||
let own = inputs + usize::from(kind.has_result());
|
||||
match s {
|
||||
_ if s < inputs => Some(super::stations::INPUT + s),
|
||||
_ if s < own => Some(super::stations::RESULT),
|
||||
_ if s < own + 27 => Some(9 + s - own),
|
||||
_ if s < own + 36 => Some(s - own - 27),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The workstation screen of a menu type a server opens.
|
||||
pub(super) fn remote_station_kind(menu: &str) -> Option<super::stations::Kind> {
|
||||
use super::stations::Kind;
|
||||
Some(match menu {
|
||||
"minecraft:loom" => Kind::Loom,
|
||||
"minecraft:stonecutter" => Kind::Stonecutter,
|
||||
"minecraft:grindstone" => Kind::Grindstone,
|
||||
"minecraft:anvil" => Kind::Anvil,
|
||||
"minecraft:smithing" => Kind::Smithing,
|
||||
"minecraft:enchantment" => Kind::Enchanting,
|
||||
"minecraft:beacon" => Kind::Beacon,
|
||||
"minecraft:cartography_table" => Kind::Cartography,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn open_menu_name(&self, container: i32) -> String {
|
||||
match self.remote.as_ref().and_then(|r| r.menu.as_ref()) {
|
||||
Some((id, name)) if *id == container && container != 0 => name.clone(),
|
||||
@@ -1305,6 +1390,12 @@ impl Game<'_> {
|
||||
}
|
||||
fn set_menu_slot(&mut self, container: i32, slot: i32, item: Option<ItemStack>) {
|
||||
let menu = self.open_menu_name(container);
|
||||
if menu == "minecraft:lectern" {
|
||||
if slot == 0 {
|
||||
self.remote_lectern_book(item);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if container != 0 && menu == "inventory" {
|
||||
return;
|
||||
}
|
||||
@@ -1315,6 +1406,9 @@ impl Game<'_> {
|
||||
return; // the result slot is recomputed from the grid
|
||||
}
|
||||
*self.slot_mut(internal) = item;
|
||||
if internal >= super::stations::INPUT && self.station.is_some() {
|
||||
self.remote_station_slot_changed(internal);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_packet(&mut self, packet: C) -> Result<()> {
|
||||
@@ -1960,6 +2054,12 @@ impl Game<'_> {
|
||||
}
|
||||
self.remote_synced();
|
||||
}
|
||||
C::ContainerSetData(p) if self.open_menu_name(p.container) == "minecraft:lectern" => {
|
||||
self.remote_lectern_page(i32::from(p.value));
|
||||
}
|
||||
C::ContainerSetData(p) if self.remote_station_open(p.container) => {
|
||||
self.remote_station_data(usize::try_from(p.id).unwrap_or(usize::MAX), p.value);
|
||||
}
|
||||
C::ContainerSetData(p) => {
|
||||
let v = i32::from(p.value);
|
||||
match self
|
||||
@@ -1973,6 +2073,12 @@ impl Game<'_> {
|
||||
3 => f.cooking_total = v,
|
||||
_ => {}
|
||||
},
|
||||
// CrafterBlockEntity.containerData.
|
||||
Some(BlockEntity::Crafter(c)) => match usize::try_from(p.id) {
|
||||
Ok(k @ 0..9) => c.disabled[k] = v == 1,
|
||||
Ok(9) => c.triggered = v == 1,
|
||||
_ => {}
|
||||
},
|
||||
// BrewingStandBlockEntity.dataAccess.
|
||||
Some(BlockEntity::Brewing(b)) => match p.id {
|
||||
0 => b.brew_time = v,
|
||||
@@ -1990,6 +2096,7 @@ impl Game<'_> {
|
||||
C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p),
|
||||
C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p),
|
||||
C::MerchantOffers(p) => self.remote_merchant_offers(p),
|
||||
C::ContainerClose(_) if self.remote_lectern_closed() => {}
|
||||
C::ContainerClose(_) => {
|
||||
if self.screen == Screen::Inventory {
|
||||
self.remote_close_local();
|
||||
@@ -3836,6 +3943,10 @@ impl Game<'_> {
|
||||
/// engine doesn't model sends the clicks unpredicted. False when a click's
|
||||
/// slot isn't one of the menu's.
|
||||
pub(super) fn remote_menu_ops(&mut self, ops: &[(Option<usize>, i32, Input)]) -> bool {
|
||||
// CrafterScreen.slotClicked: a slot toggle goes out before the click.
|
||||
if let [(Some(slot), button, input)] = ops {
|
||||
self.crafter_slot_clicked(*slot, *button, *input);
|
||||
}
|
||||
let (container, menu) = self.remote_menu();
|
||||
let mut clicks = Vec::with_capacity(ops.len());
|
||||
for &(slot, button, input) in ops {
|
||||
@@ -3988,13 +4099,8 @@ impl Game<'_> {
|
||||
r.menu = None;
|
||||
r.menu_title = None;
|
||||
}
|
||||
if self
|
||||
.station
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.kind == super::stations::Kind::Merchant)
|
||||
{
|
||||
self.station = None;
|
||||
}
|
||||
// The client's menu has no level access: what it holds is the server's.
|
||||
self.station = None;
|
||||
self.craft_size = 2;
|
||||
if let Some(key) = self.container.take() {
|
||||
// Server containers stay renderable but lose their copied slots.
|
||||
@@ -4068,6 +4174,27 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.and_then(|r| r.use_target)
|
||||
.map(|t| (t[0], t[1], t[2]));
|
||||
if menu == "minecraft:lectern" {
|
||||
// LecternScreen: the book and page come in the menu's content and data.
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.menu = Some((p.container, menu));
|
||||
}
|
||||
self.remote_open_lectern(target.unwrap_or_default());
|
||||
return;
|
||||
}
|
||||
if let Some(kind) = Self::remote_station_kind(&menu) {
|
||||
let title = plain(
|
||||
&p.title,
|
||||
&self
|
||||
.remote
|
||||
.as_ref()
|
||||
.map(|r| r.lang.clone())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
let pos = target.map_or([0, 0, 0], |t| [t.0, t.1, t.2]);
|
||||
self.remote_open_station(p.container, menu, kind, title, pos);
|
||||
return;
|
||||
}
|
||||
if menu == "minecraft:merchant" {
|
||||
// A trading window: its offers follow in a MerchantOffers packet.
|
||||
let title = plain(
|
||||
@@ -4107,6 +4234,8 @@ impl Game<'_> {
|
||||
horizon_client::brewing::BrewingStand::new(),
|
||||
))),
|
||||
"minecraft:generic_3x3" => Some(BlockEntity::Chest(vec![None; 9])),
|
||||
// CrafterMenu: the disabled slots and triggered come in ContainerSetData.
|
||||
"minecraft:crafter_3x3" => Some(BlockEntity::Crafter(Default::default())),
|
||||
m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => {
|
||||
let rows = m
|
||||
.strip_prefix("minecraft:generic_9x")
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! A server's workstation menus on this client: the server opens the menu
|
||||
//! (`ClientboundOpenScreenPacket` with the station's `MenuType`), the
|
||||
//! station screen draws it, and its clicks and buttons are predicted on the
|
||||
//! menu engine (`Game::menu_session`) and sent, as
|
||||
//! `MultiPlayerGameMode.handleContainerInput` and `handleInventoryButtonClick`
|
||||
//! do. The menu's client-side `slotsChanged` follows the server's slots, and
|
||||
//! its data slots come in `ClientboundContainerSetDataPacket`.
|
||||
use super::{
|
||||
Game, Screen,
|
||||
stations::{Kind, Station},
|
||||
};
|
||||
use horizon_protocol::packets::play::{self, Serverbound as S};
|
||||
|
||||
impl Game<'_> {
|
||||
/// The server opened workstation menu `menu` in window `container`.
|
||||
pub(super) fn remote_open_station(
|
||||
&mut self,
|
||||
container: i32,
|
||||
menu: String,
|
||||
kind: Kind,
|
||||
title: String,
|
||||
pos: [i32; 3],
|
||||
) {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.menu = Some((container, menu));
|
||||
r.menu_title = Some(title);
|
||||
}
|
||||
self.craft_size = 2;
|
||||
self.container = None;
|
||||
self.station = Some(Station::new_kind(kind, pos));
|
||||
self.screen = Screen::Inventory;
|
||||
self.capture(false);
|
||||
}
|
||||
|
||||
/// Window `container` is the server's workstation menu, open here.
|
||||
pub(super) fn remote_station_open(&self, container: i32) -> bool {
|
||||
self.station.is_some()
|
||||
&& self
|
||||
.remote
|
||||
.as_ref()
|
||||
.and_then(|r| r.menu.as_ref())
|
||||
.is_some_and(|(id, name)| {
|
||||
*id == container && Self::remote_station_kind(name).is_some()
|
||||
})
|
||||
}
|
||||
|
||||
/// The server set station slot `internal`: the client menu's
|
||||
/// `Slot.set` runs its container's `setChanged`, so the loom lists the
|
||||
/// patterns its inputs allow and the stonecutter the recipes of its input.
|
||||
pub(super) fn remote_station_slot_changed(&mut self, internal: usize) {
|
||||
if !self.station.as_ref().is_some_and(|s| {
|
||||
matches!(
|
||||
s.kind,
|
||||
Kind::Loom
|
||||
| Kind::Stonecutter
|
||||
| Kind::Grindstone
|
||||
| Kind::Anvil
|
||||
| Kind::Smithing
|
||||
| Kind::Cartography
|
||||
)
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
self.menu_session(|menu, env, to_menu| {
|
||||
let i = to_menu(internal)?;
|
||||
let stack = menu.slot(i).cloned();
|
||||
menu.set_slot(env, i, stack);
|
||||
Some(true)
|
||||
});
|
||||
// AnvilScreen.slotChanged: the box shows the new input's name, which
|
||||
// its responder sends.
|
||||
self.remote_anvil_rename();
|
||||
}
|
||||
|
||||
/// `AbstractContainerMenu.setData` from the server.
|
||||
pub(super) fn remote_station_data(&mut self, id: usize, value: i16) {
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
match (s.kind, id) {
|
||||
// LoomMenu.selectedBannerPatternIndex.
|
||||
(Kind::Loom, 0) => s.loom.selected = usize::try_from(value).ok(),
|
||||
// StonecutterMenu.selectedRecipeIndex.
|
||||
(Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(),
|
||||
// AnvilMenu.cost.
|
||||
(Kind::Anvil, 0) => s.anvil.cost = i32::from(value),
|
||||
// EnchantmentMenu: costs, the seed (the screen's glyph names),
|
||||
// the clues' enchantments and levels.
|
||||
(Kind::Enchanting, 0..3) => s.offers.costs[id] = i32::from(value),
|
||||
(Kind::Enchanting, 3) => self.level.xp_seed = i32::from(value),
|
||||
(Kind::Enchanting, 4..7) => {
|
||||
let name = self.remote.as_ref().and_then(|r| {
|
||||
r.registries
|
||||
.name("minecraft:enchantment", i32::from(value))
|
||||
.map(std::sync::Arc::<str>::from)
|
||||
});
|
||||
let level = s.offers.clues[id - 4].as_ref().map_or(1, |(_, l)| *l);
|
||||
s.offers.clues[id - 4] = name.map(|n| (n, level));
|
||||
}
|
||||
(Kind::Enchanting, 7..10) => {
|
||||
if let Some((_, level)) = s.offers.clues[id - 7].as_mut() {
|
||||
*level = value.max(0) as u32;
|
||||
}
|
||||
}
|
||||
// BeaconMenu: the levels, then the powers (BeaconScreen's
|
||||
// dataChanged shows the menu's).
|
||||
(Kind::Beacon, 0) => s.beacon_levels = Some(i32::from(value)),
|
||||
(Kind::Beacon, 1 | 2) => {
|
||||
let effect = self.remote_effect_id(i32::from(value) - 1);
|
||||
let index =
|
||||
effect.and_then(|e| super::beacon::EFFECTS.iter().position(|(n, _)| *n == e));
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
s.beacon[id - 1] = index;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `AnvilScreen.onNameChanged` on a server: the rename box's text (blank
|
||||
/// when it is the input's own name) goes to the server when the menu's
|
||||
/// `setItemName` takes it.
|
||||
pub(super) fn remote_anvil_rename(&mut self) {
|
||||
if self.remote.is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(s) = self
|
||||
.station
|
||||
.as_ref()
|
||||
.filter(|s| s.kind == Kind::Anvil && s.inputs[0].is_some())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let name = self.anvil_item_name(s);
|
||||
if s.anvil_sent.as_deref() == Some(&name) {
|
||||
return;
|
||||
}
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
s.anvil_sent = Some(name.clone());
|
||||
}
|
||||
self.send(S::RenameItem(play::RenameItem { name }));
|
||||
}
|
||||
|
||||
/// `MultiPlayerGameMode.handleInventoryButtonClick`: the screen already
|
||||
/// ran `clickMenuButton` on its own menu.
|
||||
pub(super) fn remote_station_button(&self, button: i32) {
|
||||
if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref())
|
||||
&& self.remote_station_open(*container)
|
||||
{
|
||||
self.send(S::ContainerButtonClick(play::ContainerButtonClick {
|
||||
container: *container,
|
||||
button,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub(super) const HELP: &[&str] = &[
|
||||
"use X Y Z open the block's menu as if right-clicked",
|
||||
"click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)",
|
||||
"click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner",
|
||||
"book [next|back|take|done] the open book or lectern: its page, or press one of its buttons",
|
||||
"type TEXT | type-back type into the anvil name box / delete one character",
|
||||
"enchant ID LEVEL enchant the held item (books store the enchantment)",
|
||||
"potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)",
|
||||
@@ -136,6 +137,7 @@ impl Game<'_> {
|
||||
self.apply_equipment();
|
||||
ok()
|
||||
}
|
||||
"book" => Ok(Some(self.book_control(words.get(1).copied())?)),
|
||||
"potion" => {
|
||||
let stack = ItemStack::new(&id(arg(1)?), 1).with_potion(&id(arg(2)?));
|
||||
let rest = self.give(stack);
|
||||
|
||||
@@ -13,7 +13,6 @@ use horizon_client::{
|
||||
stations::{self, AnvilResult, EnchantOffers},
|
||||
};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Slot ids of the open station: inputs from 600, the result at 650.
|
||||
pub(super) const INPUT: usize = 600;
|
||||
@@ -36,7 +35,7 @@ pub(super) enum Kind {
|
||||
Loom,
|
||||
}
|
||||
impl Kind {
|
||||
fn from_block(name: &str) -> Option<Self> {
|
||||
pub(super) fn from_block(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"minecraft:enchanting_table" => Self::Enchanting,
|
||||
"minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => {
|
||||
@@ -51,7 +50,7 @@ impl Kind {
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn inputs(self) -> usize {
|
||||
pub(super) fn inputs(self) -> usize {
|
||||
match self {
|
||||
Self::Smithing | Self::Loom => 3,
|
||||
Self::Stonecutter | Self::Beacon => 1,
|
||||
@@ -71,7 +70,7 @@ impl Kind {
|
||||
Self::Loom => "gui/container/loom",
|
||||
}
|
||||
}
|
||||
fn title_key(self) -> &'static str {
|
||||
pub(super) fn title_key(self) -> &'static str {
|
||||
match self {
|
||||
Self::Enchanting => "container.enchant",
|
||||
Self::Anvil => "container.repair",
|
||||
@@ -108,6 +107,10 @@ impl Kind {
|
||||
};
|
||||
table[i.min(table.len() - 1)]
|
||||
}
|
||||
/// Whether the menu has a result slot after its inputs.
|
||||
pub(super) fn has_result(self) -> bool {
|
||||
self.result_pos().is_some()
|
||||
}
|
||||
fn result_pos(self) -> Option<(f32, f32)> {
|
||||
match self {
|
||||
Self::Enchanting => None,
|
||||
@@ -128,18 +131,20 @@ pub(super) struct Station {
|
||||
pub(super) pos: [i32; 3],
|
||||
pub(super) inputs: Vec<Option<ItemStack>>,
|
||||
pub(super) result: Option<ItemStack>,
|
||||
offers: EnchantOffers,
|
||||
pub(super) offers: EnchantOffers,
|
||||
bookcases: i32,
|
||||
anvil: AnvilResult,
|
||||
pub(super) anvil: AnvilResult,
|
||||
/// Anvil rename box text.
|
||||
pub(super) name: String,
|
||||
/// Stonecutter: recipe indices for the input, selection and first shown index.
|
||||
recipes: Vec<usize>,
|
||||
selected: Option<usize>,
|
||||
/// Stonecutter: the menu's recipe list (horizon_client::menu), its
|
||||
/// `selectedRecipeIndex` and the screen's first shown index.
|
||||
pub(super) stone: horizon_client::menu::Stonecutter,
|
||||
pub(super) selected: Option<usize>,
|
||||
start: usize,
|
||||
input_item: Option<Arc<str>>,
|
||||
/// Anvil: the input the rename box was last filled from.
|
||||
anvil_last: Option<ItemStack>,
|
||||
/// Anvil on a server: the name last sent (the client menu's `itemName`).
|
||||
pub(super) anvil_sent: Option<String>,
|
||||
/// When the screen opened: the rename box has the focus from then.
|
||||
opened: std::time::Instant,
|
||||
pub(super) last_sound: u64,
|
||||
@@ -147,6 +152,8 @@ pub(super) struct Station {
|
||||
pub(super) merchant: Option<Box<super::trading::MerchantState>>,
|
||||
/// Beacon menu: the selected primary and secondary power (EFFECTS index).
|
||||
pub(super) beacon: [Option<usize>; 2],
|
||||
/// A server's beacon menu: the pyramid's levels (its data slot 0).
|
||||
pub(super) beacon_levels: Option<i32>,
|
||||
/// The loom's patterns, selection and scroller (game/loom.rs).
|
||||
pub(super) loom: super::loom::LoomState,
|
||||
}
|
||||
@@ -161,21 +168,29 @@ impl Station {
|
||||
bookcases: 0,
|
||||
anvil: AnvilResult::default(),
|
||||
name: String::new(),
|
||||
recipes: Vec::new(),
|
||||
stone: Default::default(),
|
||||
selected: None,
|
||||
start: 0,
|
||||
input_item: None,
|
||||
anvil_last: None,
|
||||
anvil_sent: None,
|
||||
opened: std::time::Instant::now(),
|
||||
last_sound: 0,
|
||||
merchant: None,
|
||||
beacon: [None; 2],
|
||||
beacon_levels: None,
|
||||
loom: Default::default(),
|
||||
}
|
||||
}
|
||||
pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self {
|
||||
Self::new(kind, pos)
|
||||
}
|
||||
/// `StonecutterScreen.containerChanged`: without recipes to show, the
|
||||
/// list scrolls back to the top.
|
||||
pub(super) fn stonecutter_changed(&mut self) {
|
||||
if self.inputs[0].is_none() || self.stone.recipes.is_empty() {
|
||||
self.start = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 108x19 enchantment button `i` (relative to the GUI origin).
|
||||
@@ -323,6 +338,10 @@ impl Game<'_> {
|
||||
let Some(mut station) = self.station.take() else {
|
||||
return;
|
||||
};
|
||||
if self.remote.is_some() && station.kind != Kind::Merchant {
|
||||
// A server's workstation: its removed() gives the inputs back.
|
||||
return;
|
||||
}
|
||||
if let Some(m) = station.merchant.as_mut() {
|
||||
self.merchant_closed(m);
|
||||
}
|
||||
@@ -375,7 +394,7 @@ impl Game<'_> {
|
||||
_ => &mut self.scratch_slot,
|
||||
}
|
||||
}
|
||||
fn count_bookshelves(&self, pos: [i32; 3]) -> i32 {
|
||||
pub(super) fn count_bookshelves(&self, pos: [i32; 3]) -> i32 {
|
||||
let tags = &self.res.items().block_tags;
|
||||
let is = |p: [i32; 3], tag: &str| {
|
||||
let name = &self
|
||||
@@ -399,7 +418,7 @@ impl Game<'_> {
|
||||
.count() as i32
|
||||
}
|
||||
/// The anvil name the menu works with (`AnvilScreen.onNameChanged`).
|
||||
fn anvil_item_name(&self, s: &Station) -> String {
|
||||
pub(super) fn anvil_item_name(&self, s: &Station) -> String {
|
||||
match &s.inputs[0] {
|
||||
Some(input)
|
||||
if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) =>
|
||||
@@ -419,6 +438,16 @@ impl Game<'_> {
|
||||
let data = self.res.stations();
|
||||
let items = self.res.items();
|
||||
match s.kind {
|
||||
// A server's table: its data slots carry the offers, and its
|
||||
// client menu only clears them without an enchantable item.
|
||||
Kind::Enchanting if self.remote.is_some() => {
|
||||
let enchantable = s.inputs[0].as_ref().is_some_and(|i| {
|
||||
data.enchantments.enchantable(&i.item) > 0 && i.enchantments().is_empty()
|
||||
});
|
||||
if !enchantable {
|
||||
s.offers = Default::default();
|
||||
}
|
||||
}
|
||||
Kind::Enchanting => {
|
||||
s.bookcases = self.count_bookshelves(s.pos);
|
||||
s.offers = stations::enchant_offers(
|
||||
@@ -465,35 +494,9 @@ impl Game<'_> {
|
||||
// The menu engine keeps the merchant's result (Game::menu_session).
|
||||
Kind::Merchant => {}
|
||||
Kind::Beacon => {}
|
||||
Kind::Cartography => s.result = self.cartography_result(&s),
|
||||
// The menu engine keeps the loom's state (Game::menu_session).
|
||||
Kind::Loom => {}
|
||||
Kind::Stonecutter => {
|
||||
let item = s.inputs[0].as_ref().map(|i| i.item.clone());
|
||||
if item != s.input_item {
|
||||
s.input_item = item;
|
||||
s.selected = None;
|
||||
s.start = 0;
|
||||
s.recipes = match &s.inputs[0] {
|
||||
Some(input) => data
|
||||
.recipes
|
||||
.stonecutting
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, r)| r.input.test(input))
|
||||
.map(|(i, _)| i)
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
}
|
||||
s.result = match (s.selected, &s.inputs[0]) {
|
||||
(Some(i), Some(_)) => s
|
||||
.recipes
|
||||
.get(i)
|
||||
.map(|&r| data.recipes.stonecutting[r].result.clone()),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
// The menu engine keeps the cartography table's, the loom's and
|
||||
// the stonecutter's state (Game::menu_session).
|
||||
Kind::Cartography | Kind::Loom | Kind::Stonecutter => {}
|
||||
}
|
||||
self.station = Some(s);
|
||||
}
|
||||
@@ -505,7 +508,6 @@ impl Game<'_> {
|
||||
}
|
||||
/// `Slot.mayPlace` and `getMaxStackSize` for station slots.
|
||||
fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) {
|
||||
let data = self.data();
|
||||
if slot >= super::mount_menu::SADDLE {
|
||||
return self.mount_slot_rules(slot, stack);
|
||||
}
|
||||
@@ -528,24 +530,7 @@ impl Game<'_> {
|
||||
if slot == RESULT {
|
||||
return (false, 64);
|
||||
}
|
||||
let i = slot - INPUT;
|
||||
match s.kind {
|
||||
Kind::Enchanting if i == 0 => (true, 1),
|
||||
Kind::Beacon => (super::beacon::is_payment(&stack.item), 1),
|
||||
Kind::Loom => (false, 64),
|
||||
Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64),
|
||||
Kind::Cartography => (
|
||||
matches!(
|
||||
&*stack.item,
|
||||
"minecraft:paper" | "minecraft:map" | "minecraft:glass_pane"
|
||||
),
|
||||
64,
|
||||
),
|
||||
Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64),
|
||||
Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64),
|
||||
Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64),
|
||||
_ => (true, 64),
|
||||
}
|
||||
(s.kind != Kind::Loom, 64)
|
||||
}
|
||||
/// `AbstractContainerMenu.doClick` PICKUP on a filtered slot.
|
||||
pub(super) fn click_filtered(&mut self, slot: usize, right: bool) {
|
||||
@@ -644,112 +629,80 @@ impl Game<'_> {
|
||||
}
|
||||
stack.count != start
|
||||
}
|
||||
/// The player inventory in menu order: main rows, then the hotbar.
|
||||
fn player_slots() -> Vec<usize> {
|
||||
(9..36).chain(0..9).collect()
|
||||
/// After an anvil or smithing click on the menu engine: the anvil's cost
|
||||
/// and state back into the station and the rename box following the
|
||||
/// input (`AnvilScreen.slotChanged`), then the rest of a taken result's
|
||||
/// `onTake` (the levels, the anvil's wear, the use sound) unless a
|
||||
/// server does it.
|
||||
pub(super) fn combiner_session_end(
|
||||
&mut self,
|
||||
menu: &horizon_client::menu::Menu,
|
||||
predicting: bool,
|
||||
) {
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let (pos, kind) = (s.pos, s.kind);
|
||||
if kind == Kind::Anvil {
|
||||
s.anvil.cost = menu.data[0];
|
||||
s.anvil.repair_item_count_cost = menu.anvil.repair_count;
|
||||
s.anvil.only_renaming = menu.anvil.only_renaming;
|
||||
s.anvil.result = s.result.clone();
|
||||
}
|
||||
self.station_after_input();
|
||||
if !menu.combined || predicting {
|
||||
return;
|
||||
}
|
||||
if kind == Kind::Smithing {
|
||||
self.level_event_at(1044, pos, 0);
|
||||
return;
|
||||
}
|
||||
self.give_levels(menu.level_change);
|
||||
if self.anvil_used(pos, self.creative) {
|
||||
self.close_station();
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
}
|
||||
}
|
||||
/// A shift-click: `AbstractContainerMenu.doClick`'s QUICK_MOVE repeats
|
||||
/// `quickMoveStack` while it moves something and the slot still holds the
|
||||
/// same item.
|
||||
fn quick_move(&mut self, slot: usize) {
|
||||
while let Some(item) = self.slot_mut(slot).as_ref().map(|s| s.item.clone())
|
||||
&& self.quick_move_once(slot)
|
||||
&& self.slot_mut(slot).as_ref().is_some_and(|s| s.item == item)
|
||||
{}
|
||||
}
|
||||
/// The station menu's `quickMoveStack` for one slot (`EnchantmentMenu`,
|
||||
/// `BeaconMenu`, `GrindstoneMenu`, `StonecutterMenu`,
|
||||
/// `CartographyTableMenu`, and `ItemCombinerMenu` with `SmithingMenu`'s
|
||||
/// `canMoveIntoInputSlots`); whether the stack's count changed. Each
|
||||
/// rule that names its target slots moves nowhere else when they are full.
|
||||
fn quick_move_once(&mut self, slot: usize) -> bool {
|
||||
let Some(kind) = self.station.as_ref().map(|s| s.kind) else {
|
||||
return false;
|
||||
};
|
||||
let Some(mut stack) = self.slot_mut(slot).take() else {
|
||||
return false;
|
||||
};
|
||||
let start = stack.count;
|
||||
let empty = |game: &mut Self, i: usize| game.station_slot_mut(INPUT + i).is_none();
|
||||
// The other half of the inventory: main rows to the hotbar and back.
|
||||
let halves: Vec<usize> = if slot < 9 {
|
||||
(9..36).collect()
|
||||
} else {
|
||||
(0..9).collect()
|
||||
};
|
||||
if slot >= INPUT {
|
||||
// An input slot: into the inventory, the hotbar's last slot first
|
||||
// where vanilla moves in reverse.
|
||||
let reverse = matches!(kind, Kind::Enchanting | Kind::Beacon);
|
||||
self.move_to(&mut stack, &Self::player_slots(), reverse);
|
||||
} else {
|
||||
match kind {
|
||||
Kind::Enchanting => {
|
||||
if &*stack.item == "minecraft:lapis_lazuli" {
|
||||
self.move_to(&mut stack, &[INPUT + 1], true);
|
||||
} else if empty(self, 0) {
|
||||
*self.station_slot_mut(INPUT) = Some(ItemStack {
|
||||
count: 1,
|
||||
..stack.clone()
|
||||
});
|
||||
stack.count -= 1;
|
||||
}
|
||||
/// `AnvilMenu.onTake`'s level part: out of creative a 12% chance
|
||||
/// (`AnvilBlock.damage`) to wear the anvil a stage, or break a damaged one
|
||||
/// (level event 1029); otherwise level event 1030. True when it broke.
|
||||
pub(super) fn anvil_used(&mut self, pos: [i32; 3], creative: bool) -> bool {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let name = self.res.facts().get(state).name.clone();
|
||||
let anvil = matches!(
|
||||
&*name,
|
||||
"minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil"
|
||||
);
|
||||
if !creative && anvil && self.world.random.next_float() < 0.12 {
|
||||
match &*name {
|
||||
"minecraft:anvil" => {
|
||||
let _ = self.set_state_named(pos, "minecraft:chipped_anvil", &["facing"]);
|
||||
}
|
||||
Kind::Beacon => {
|
||||
if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1
|
||||
{
|
||||
self.move_to(&mut stack, &[INPUT], false);
|
||||
} else {
|
||||
self.move_to(&mut stack, &halves, false);
|
||||
}
|
||||
"minecraft:chipped_anvil" => {
|
||||
let _ = self.set_state_named(pos, "minecraft:damaged_anvil", &["facing"]);
|
||||
}
|
||||
Kind::Grindstone => {
|
||||
if empty(self, 0) || empty(self, 1) {
|
||||
self.move_to(&mut stack, &[INPUT, INPUT + 1], false);
|
||||
} else {
|
||||
self.move_to(&mut stack, &halves, false);
|
||||
}
|
||||
_ => {
|
||||
let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air);
|
||||
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
|
||||
self.level_event_at(1029, pos, 0);
|
||||
return true;
|
||||
}
|
||||
Kind::Stonecutter => {
|
||||
if self.data().recipes.stonecutter(&stack).is_empty() {
|
||||
self.move_to(&mut stack, &halves, false);
|
||||
} else {
|
||||
self.move_to(&mut stack, &[INPUT], false);
|
||||
}
|
||||
}
|
||||
Kind::Cartography => {
|
||||
if super::maps::map_id(&stack).is_some() {
|
||||
self.move_to(&mut stack, &[INPUT], false);
|
||||
} else if matches!(
|
||||
&*stack.item,
|
||||
"minecraft:paper" | "minecraft:map" | "minecraft:glass_pane"
|
||||
) {
|
||||
self.move_to(&mut stack, &[INPUT + 1], false);
|
||||
} else {
|
||||
self.move_to(&mut stack, &halves, false);
|
||||
}
|
||||
}
|
||||
Kind::Anvil | Kind::Smithing => {
|
||||
let inputs: Vec<usize> = (0..kind.inputs()).map(|i| INPUT + i).collect();
|
||||
// ItemCombinerMenu.canMoveIntoInputSlots: always for the
|
||||
// anvil; the smithing table needs an empty slot whose
|
||||
// ingredient test takes the stack.
|
||||
let into_inputs = kind == Kind::Anvil
|
||||
|| (0..3).any(|i| {
|
||||
empty(self, i) && self.data().recipes.smithing_accepts(i, &stack)
|
||||
});
|
||||
let targets = if into_inputs { &inputs } else { &halves };
|
||||
self.move_to(&mut stack, targets, false);
|
||||
}
|
||||
// Their clicks run on the menu engine.
|
||||
Kind::Merchant | Kind::Loom => {}
|
||||
}
|
||||
}
|
||||
let moved = stack.count != start;
|
||||
if stack.count > 0 {
|
||||
*self.slot_mut(slot) = Some(stack);
|
||||
self.level_event_at(1030, pos, 0);
|
||||
false
|
||||
}
|
||||
/// The grindstone result's `onTake` with a level (`amount`: the menu's
|
||||
/// `getExperienceAmount` sum): the orbs at the block's centre
|
||||
/// (`ExperienceOrb.award`), then level event 1042, the grindstone's sound
|
||||
/// for everyone around.
|
||||
pub(super) fn grindstone_taken(&mut self, pos: [i32; 3], amount: i32) {
|
||||
let xp = stations::grindstone_xp_roll(amount, &mut self.world.random);
|
||||
if xp > 0 {
|
||||
self.spawn_orbs(pos.map(|v| f64::from(v) + 0.5), xp);
|
||||
}
|
||||
moved
|
||||
self.level_event_at(1042, pos, 0);
|
||||
}
|
||||
fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) {
|
||||
let at = [
|
||||
@@ -788,185 +741,6 @@ impl Game<'_> {
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
/// The result slot's `onTake`.
|
||||
fn take_result(&mut self) {
|
||||
let Some(mut s) = self.station.take() else {
|
||||
return;
|
||||
};
|
||||
let pos = s.pos;
|
||||
match s.kind {
|
||||
Kind::Anvil => {
|
||||
let cost = s.anvil.cost;
|
||||
let repair = s.anvil.repair_item_count_cost;
|
||||
if repair > 0 {
|
||||
if let Some(a) = s.inputs[1].as_mut()
|
||||
&& a.count > repair
|
||||
{
|
||||
a.count -= repair;
|
||||
} else {
|
||||
s.inputs[1] = None;
|
||||
}
|
||||
} else if !s.anvil.only_renaming {
|
||||
s.inputs[1] = None;
|
||||
}
|
||||
s.inputs[0] = None;
|
||||
s.name.clear();
|
||||
if !self.creative {
|
||||
self.give_levels(-cost);
|
||||
}
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
if !self.creative && self.world.random.next_float() < 0.12 {
|
||||
// AnvilBlock.damage
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let name = self.res.facts().get(state).name.clone();
|
||||
let next = match &*name {
|
||||
"minecraft:anvil" => Some("minecraft:chipped_anvil"),
|
||||
"minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"),
|
||||
_ => None,
|
||||
};
|
||||
match next {
|
||||
Some(next) => {
|
||||
let _ = self.set_state_named(pos, next, &["facing"]);
|
||||
self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch);
|
||||
}
|
||||
None => {
|
||||
let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air);
|
||||
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
|
||||
self.play_at("minecraft:block.anvil.destroy", pos, 1.0, pitch);
|
||||
self.station = Some(s);
|
||||
self.close_station();
|
||||
self.screen = Screen::Playing;
|
||||
self.capture(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch);
|
||||
}
|
||||
}
|
||||
Kind::Grindstone => {
|
||||
let (a, b) = (s.inputs[0].take(), s.inputs[1].take());
|
||||
let mut random = LegacyRandom::new(self.world.random.next_long());
|
||||
let xp = stations::grindstone_experience(
|
||||
&self.res.stations().enchantments,
|
||||
&mut random,
|
||||
a.as_ref(),
|
||||
b.as_ref(),
|
||||
);
|
||||
if xp > 0 {
|
||||
self.spawn_orbs(
|
||||
[
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
],
|
||||
xp,
|
||||
);
|
||||
}
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch);
|
||||
}
|
||||
Kind::Smithing => {
|
||||
for slot in s.inputs.iter_mut() {
|
||||
if let Some(x) = slot.as_mut() {
|
||||
x.count -= 1;
|
||||
if x.count == 0 {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch);
|
||||
}
|
||||
Kind::Stonecutter => {
|
||||
if let Some(x) = s.inputs[0].as_mut() {
|
||||
x.count -= 1;
|
||||
if x.count == 0 {
|
||||
s.inputs[0] = None;
|
||||
}
|
||||
}
|
||||
if s.last_sound != self.ticks {
|
||||
s.last_sound = self.ticks;
|
||||
self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
Kind::Merchant => {}
|
||||
Kind::Beacon => {}
|
||||
Kind::Cartography => {
|
||||
for slot in &mut s.inputs {
|
||||
if let Some(x) = slot.as_mut() {
|
||||
x.count -= 1;
|
||||
if x.count == 0 {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.last_sound != self.ticks {
|
||||
s.last_sound = self.ticks;
|
||||
self.cartography_taken(pos);
|
||||
}
|
||||
}
|
||||
Kind::Loom => {}
|
||||
Kind::Enchanting => {}
|
||||
}
|
||||
self.station = Some(s);
|
||||
self.station_changed();
|
||||
}
|
||||
fn click_result(&mut self, shift: bool) {
|
||||
loop {
|
||||
let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else {
|
||||
return;
|
||||
};
|
||||
if !self.may_take_result() {
|
||||
return;
|
||||
}
|
||||
let result = if self
|
||||
.station
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.kind == Kind::Cartography)
|
||||
{
|
||||
self.cartography_post(result)
|
||||
} else {
|
||||
result
|
||||
};
|
||||
if shift {
|
||||
let mut stack = result.clone();
|
||||
let player = Self::player_slots();
|
||||
// Simulate first so nothing is lost when the inventory is full.
|
||||
let saved: Vec<Option<ItemStack>> = self.inventory.clone();
|
||||
self.move_to(&mut stack, &player, true);
|
||||
if stack.count > 0 {
|
||||
self.inventory = saved;
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
match &mut self.carried {
|
||||
None => self.carried = Some(result.clone()),
|
||||
Some(c)
|
||||
if c.same_item_same_components(&result)
|
||||
&& c.count + result.count
|
||||
<= self.res.items().get(&c.item).map_or(64, |i| i.max_stack) =>
|
||||
{
|
||||
c.count += result.count
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
}
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
s.result = None;
|
||||
}
|
||||
self.take_result();
|
||||
let again = shift
|
||||
&& self
|
||||
.station
|
||||
.as_ref()
|
||||
.and_then(|s| s.result.as_ref())
|
||||
.is_some_and(|r| r.item == result.item);
|
||||
if !again {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `EnchantmentMenu.clickMenuButton`.
|
||||
fn click_enchant(&mut self, button: usize) {
|
||||
let Some(s) = self.station.as_ref() else {
|
||||
@@ -987,6 +761,11 @@ impl Game<'_> {
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.remote.is_some() {
|
||||
// EnchantmentScreen.mouseClicked: the client menu took it, the server enchants.
|
||||
self.remote_station_button(button as i32);
|
||||
return;
|
||||
}
|
||||
let Some(enchanted) = stations::apply_enchantment(
|
||||
&self.res.stations().enchantments,
|
||||
self.res.items(),
|
||||
@@ -1036,7 +815,7 @@ impl Game<'_> {
|
||||
})
|
||||
.collect(),
|
||||
Kind::Stonecutter if s.inputs[0].is_some() => (s.start
|
||||
..(s.start + 12).min(s.recipes.len()))
|
||||
..(s.start + 12).min(s.stone.recipes.len()))
|
||||
.map(|index| {
|
||||
let p = index - s.start;
|
||||
[
|
||||
@@ -1089,64 +868,21 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if kind == Kind::Stonecutter
|
||||
&& let Some(s) = self.station.as_ref()
|
||||
&& s.inputs[0].is_some()
|
||||
{
|
||||
for index in s.start..(s.start + 12).min(s.recipes.len()) {
|
||||
let p = index - s.start;
|
||||
let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0);
|
||||
if inside(local, x, y, 16.0, 18.0) {
|
||||
if s.selected != Some(index) {
|
||||
if let Some(st) = self.station.as_mut() {
|
||||
st.selected = Some(index);
|
||||
}
|
||||
self.audio.play(
|
||||
"minecraft:ui.stonecutter.select_recipe",
|
||||
None,
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
self.station_changed();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if kind == Kind::Stonecutter && self.stonecutter_click(local) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else {
|
||||
return true;
|
||||
};
|
||||
if self
|
||||
.station
|
||||
.as_ref()
|
||||
.is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant))
|
||||
{
|
||||
// LoomMenu, MerchantMenu and the brewing stand's BrewingStandMenu
|
||||
// clicks run on the verified menu engine.
|
||||
let input = if shift {
|
||||
horizon_client::menu::Input::QuickMove
|
||||
} else {
|
||||
horizon_client::menu::Input::Pickup
|
||||
};
|
||||
self.menu_click(Some(slot), i32::from(right), input);
|
||||
return true;
|
||||
}
|
||||
if slot == RESULT {
|
||||
self.click_result(shift);
|
||||
return true;
|
||||
}
|
||||
if shift {
|
||||
self.quick_move(slot);
|
||||
} else if slot >= INPUT {
|
||||
self.click_filtered(slot, right);
|
||||
// Every station's clicks (and the brewing stand's) run on the
|
||||
// verified menu engine.
|
||||
let input = if shift {
|
||||
horizon_client::menu::Input::QuickMove
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if let Some(key) = self.container {
|
||||
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
|
||||
}
|
||||
self.station_after_input();
|
||||
horizon_client::menu::Input::Pickup
|
||||
};
|
||||
self.menu_click(Some(slot), i32::from(right), input);
|
||||
true
|
||||
}
|
||||
/// Recompute after slot changes; the anvil box follows its input item.
|
||||
@@ -1164,16 +900,49 @@ impl Game<'_> {
|
||||
}
|
||||
self.station_changed();
|
||||
}
|
||||
/// `StonecutterScreen.mouseClicked` on its recipe grid: `clickMenuButton`
|
||||
/// with the cell's index (an empty cell's too), and the select sound when
|
||||
/// the menu took it.
|
||||
fn stonecutter_click(&mut self, local: (f32, f32)) -> bool {
|
||||
let Some(start) = self
|
||||
.station
|
||||
.as_ref()
|
||||
.filter(|s| s.inputs[0].is_some() && !s.stone.recipes.is_empty())
|
||||
.map(|s| s.start)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
for index in start..start + 12 {
|
||||
let p = index - start;
|
||||
let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0);
|
||||
if !inside(local, x, y, 16.0, 18.0) {
|
||||
continue;
|
||||
}
|
||||
let mut taken = false;
|
||||
let flag = &mut taken;
|
||||
self.menu_session(|menu, env, _| {
|
||||
*flag = menu.button(env, index as i32);
|
||||
Some(*flag)
|
||||
});
|
||||
if taken {
|
||||
self.audio
|
||||
.play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0);
|
||||
self.remote_station_button(index as i32);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
pub(super) fn station_scroll(&mut self, d: f32) {
|
||||
self.merchant_scroll(d);
|
||||
self.loom_scroll(d);
|
||||
let Some(s) = self.station.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 {
|
||||
if s.kind != Kind::Stonecutter || s.stone.recipes.len() <= 12 {
|
||||
return;
|
||||
}
|
||||
let rows = s.recipes.len().div_ceil(4) - 3;
|
||||
let rows = s.stone.recipes.len().div_ceil(4) - 3;
|
||||
let first_row = (s.start / 4) as i32 - d.signum() as i32;
|
||||
s.start = first_row.clamp(0, rows as i32) as usize * 4;
|
||||
}
|
||||
@@ -1207,6 +976,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
self.station_changed();
|
||||
self.remote_anvil_rename();
|
||||
}
|
||||
/// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the
|
||||
/// recipe book's search box.
|
||||
@@ -1227,6 +997,7 @@ impl Game<'_> {
|
||||
ANVIL_NAME_CHARS,
|
||||
) {
|
||||
self.station_changed();
|
||||
self.remote_anvil_rename();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1740,9 +1511,9 @@ impl Game<'_> {
|
||||
}
|
||||
Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {}
|
||||
Kind::Stonecutter => {
|
||||
let display = s.inputs[0].is_some() && !s.recipes.is_empty();
|
||||
let active = display && s.recipes.len() > 12;
|
||||
let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1);
|
||||
let display = s.inputs[0].is_some() && !s.stone.recipes.is_empty();
|
||||
let active = display && s.stone.recipes.len() > 12;
|
||||
let rows = s.stone.recipes.len().div_ceil(4).saturating_sub(3).max(1);
|
||||
let offs = if active {
|
||||
(s.start / 4) as f32 / rows as f32
|
||||
} else {
|
||||
@@ -1763,13 +1534,14 @@ impl Game<'_> {
|
||||
let (start, selected) = (s.start, s.selected);
|
||||
// graphics.item: the icon only, without the count.
|
||||
let shown: Vec<(usize, ItemStack)> = (start
|
||||
..(start + 12).min(s.recipes.len()))
|
||||
..(start + 12).min(s.stone.recipes.len()))
|
||||
.map(|i| {
|
||||
(
|
||||
i,
|
||||
ItemStack {
|
||||
count: 1,
|
||||
..self.res.stations().recipes.stonecutting[s.recipes[i]]
|
||||
..self.res.stations().recipes.stonecutting
|
||||
[s.stone.recipes[i]]
|
||||
.result
|
||||
.clone()
|
||||
},
|
||||
@@ -2082,7 +1854,7 @@ impl Game<'_> {
|
||||
"bookcases": s.bookcases,
|
||||
"anvil_cost": s.anvil.cost,
|
||||
"result": s.result.as_ref().map(|r| format!("{} x{}", r.item, r.count)),
|
||||
"recipes": s.recipes.iter().map(|&i| recipes[i].id.clone()).collect::<Vec<_>>(),
|
||||
"recipes": s.stone.recipes.iter().map(|&i| recipes[i].id.clone()).collect::<Vec<_>>(),
|
||||
"selected": s.selected,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -594,12 +594,8 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Some(mode) = d.map_post_processing {
|
||||
entries.push((
|
||||
"minecraft:map_post_processing",
|
||||
Tag::String(if mode == 0 { "lock" } else { "scale" }.into()),
|
||||
));
|
||||
}
|
||||
// minecraft:map_post_processing is transient: ItemStack.CODEC never
|
||||
// saves it (only the network carries it).
|
||||
if !d.charged.is_empty() {
|
||||
entries.push((
|
||||
"minecraft:charged_projectiles",
|
||||
|
||||
@@ -455,18 +455,30 @@ impl Hub {
|
||||
let Slots::Block(pos) = m.slots else {
|
||||
return;
|
||||
};
|
||||
// AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess.
|
||||
// AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess,
|
||||
// CrafterBlockEntity.containerData.
|
||||
let data = match world.block_entities.get(&pos) {
|
||||
Some(BlockEntity::Furnace(f)) => [
|
||||
Some(BlockEntity::Furnace(f)) => vec![
|
||||
f.lit_remaining,
|
||||
f.lit_total,
|
||||
f.cooking_timer,
|
||||
f.cooking_total,
|
||||
],
|
||||
Some(BlockEntity::Brewing(b)) => [b.brew_time, b.fuel, b.total_brew_time, b.total_fuel],
|
||||
Some(BlockEntity::Brewing(b)) => {
|
||||
vec![b.brew_time, b.fuel, b.total_brew_time, b.total_fuel]
|
||||
}
|
||||
// CrafterBlockEntity.containerData: the disabled slots, then triggered.
|
||||
Some(BlockEntity::Crafter(c)) => c
|
||||
.disabled
|
||||
.iter()
|
||||
.chain([&c.triggered])
|
||||
.map(|&d| i32::from(d))
|
||||
.collect(),
|
||||
_ => return,
|
||||
}
|
||||
.map(|v| v as i16);
|
||||
.into_iter()
|
||||
.map(|v| v as i16)
|
||||
.collect::<Vec<i16>>();
|
||||
m.sent_data.resize(data.len(), i16::MIN);
|
||||
let window = m.window;
|
||||
let changed: Vec<(usize, i16)> = data
|
||||
|
||||
@@ -147,6 +147,8 @@ pub struct Guest {
|
||||
pub xp_level: i32,
|
||||
pub xp_progress: f32,
|
||||
pub xp_total: i32,
|
||||
/// `Player.enchantmentSeed` (the enchanting table's offers).
|
||||
pub xp_seed: i32,
|
||||
/// Active status effects (`LivingEntity.activeEffects`).
|
||||
pub effects: crate::effects::PlayerEffects,
|
||||
/// What the client was told of each effect: id, amplifier, flags, and
|
||||
@@ -273,6 +275,7 @@ impl Guest {
|
||||
xp_level: 0,
|
||||
xp_progress: 0.0,
|
||||
xp_total: 0,
|
||||
xp_seed: 0,
|
||||
effects: Default::default(),
|
||||
sent_effects: Vec::new(),
|
||||
menu_sent: vec![None; 46],
|
||||
@@ -418,6 +421,43 @@ pub fn stack_to_network(
|
||||
horizon_protocol::item::Component::Int(id),
|
||||
));
|
||||
}
|
||||
if d.repair_cost > 0 {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::REPAIR_COST,
|
||||
horizon_protocol::item::Component::Int(d.repair_cost as i32),
|
||||
));
|
||||
}
|
||||
if let Some(mode) = d.map_post_processing {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::MAP_POST_PROCESSING,
|
||||
horizon_protocol::item::Component::Int(i32::from(mode)),
|
||||
));
|
||||
}
|
||||
// The books a lectern shows and a guest reads.
|
||||
if !d.writable_pages.is_empty() {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::WRITABLE_BOOK_CONTENT,
|
||||
horizon_protocol::item::Component::WritableBook(d.writable_pages.clone()),
|
||||
));
|
||||
}
|
||||
if let Some(w) = &d.written {
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::WRITTEN_BOOK_CONTENT,
|
||||
horizon_protocol::item::Component::WrittenBook(
|
||||
horizon_protocol::item::WrittenBook {
|
||||
title: w.title.clone(),
|
||||
author: w.author.clone(),
|
||||
generation: i32::from(w.generation),
|
||||
pages: w
|
||||
.pages
|
||||
.iter()
|
||||
.map(|p| horizon_protocol::text::literal(p))
|
||||
.collect(),
|
||||
resolved: true,
|
||||
},
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(name) = s.custom_name() {
|
||||
stack.added.push((
|
||||
|
||||
@@ -311,6 +311,11 @@ impl Hub {
|
||||
self.sync.id(registry, name)
|
||||
}
|
||||
|
||||
/// The name of a network id in a built-in registry.
|
||||
pub fn registry_name(&self, registry: &str, id: i32) -> Option<&str> {
|
||||
self.sync.builtin.get(registry)?.name(id)
|
||||
}
|
||||
|
||||
pub fn item_id(&mut self, item: &Arc<str>) -> i32 {
|
||||
if let Some(id) = self.item_ids.get(item) {
|
||||
return *id;
|
||||
|
||||
@@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) {
|
||||
guest.xp_level = level.xp_level;
|
||||
guest.xp_progress = level.xp_progress;
|
||||
guest.xp_total = level.xp_total;
|
||||
guest.xp_seed = level.xp_seed;
|
||||
guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects);
|
||||
guest.game_mode = level.mode();
|
||||
guest.flying = level.flying;
|
||||
@@ -127,6 +128,7 @@ pub fn store(guest: &Guest, level: &mut Level) {
|
||||
level.xp_level = guest.xp_level;
|
||||
level.xp_progress = guest.xp_progress;
|
||||
level.xp_total = guest.xp_total;
|
||||
level.xp_seed = guest.xp_seed;
|
||||
level.active_effects = guest.effects.saved();
|
||||
level.game_mode = guest.game_mode;
|
||||
level.creative = guest.game_mode == 1;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -198,8 +198,10 @@ pub fn anvil_result(
|
||||
let mut repair_item_count_cost = 0;
|
||||
let mut naming_cost = 0;
|
||||
if let Some(addition) = addition {
|
||||
// addition.has(STORED_ENCHANTMENTS): only enchanted books carry that component.
|
||||
let using_book = &*addition.item == "minecraft:enchanted_book";
|
||||
// addition.has(STORED_ENCHANTMENTS): an enchanted book (its default
|
||||
// component), or any item given stored enchantments.
|
||||
let using_book = &*addition.item == "minecraft:enchanted_book"
|
||||
|| !addition.stored_enchantments().is_empty();
|
||||
if is_damageable(items, &result) && is_valid_repair_item(e, items, input, addition) {
|
||||
let max = max_damage(items, &result);
|
||||
let mut repair = (result.damage as i32).min(max / 4);
|
||||
@@ -401,13 +403,13 @@ pub fn grindstone_result(
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
/// Experience from the grindstone result slot's `getExperienceAmount`.
|
||||
pub fn grindstone_experience(
|
||||
/// The grindstone result slot's `getExperienceAmount` before its roll: the
|
||||
/// minimum costs of the inputs' non-curse enchantments.
|
||||
pub fn grindstone_xp_base(
|
||||
e: &Enchantments,
|
||||
random: &mut LegacyRandom,
|
||||
input: Option<&ItemStack>,
|
||||
additional: Option<&ItemStack>,
|
||||
) -> u32 {
|
||||
) -> i32 {
|
||||
let from = |s: Option<&ItemStack>| -> i32 {
|
||||
s.map_or(0, |s| {
|
||||
s.crafting_enchantments()
|
||||
@@ -417,7 +419,10 @@ pub fn grindstone_experience(
|
||||
.sum()
|
||||
})
|
||||
};
|
||||
let amount = from(input) + from(additional);
|
||||
from(input) + from(additional)
|
||||
}
|
||||
/// `getExperienceAmount`'s roll of the sum: `half + nextInt(half)`.
|
||||
pub fn grindstone_xp_roll(amount: i32, random: &mut LegacyRandom) -> u32 {
|
||||
if amount > 0 {
|
||||
let half = (f64::from(amount) / 2.0).ceil() as i32;
|
||||
(half + random.next_int_bound(half).unwrap_or(0)) as u32
|
||||
@@ -425,6 +430,15 @@ pub fn grindstone_experience(
|
||||
0
|
||||
}
|
||||
}
|
||||
/// Experience from the grindstone result slot's `getExperienceAmount`.
|
||||
pub fn grindstone_experience(
|
||||
e: &Enchantments,
|
||||
random: &mut LegacyRandom,
|
||||
input: Option<&ItemStack>,
|
||||
additional: Option<&ItemStack>,
|
||||
) -> u32 {
|
||||
grindstone_xp_roll(grindstone_xp_base(e, input, additional), random)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- smithing & stonecutting
|
||||
|
||||
@@ -450,6 +464,7 @@ pub struct Stonecutting {
|
||||
pub input: Ingredient,
|
||||
pub result: ItemStack,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct StationRecipes {
|
||||
pub smithing: Vec<Smithing>,
|
||||
/// Sorted by recipe id, the registry order vanilla lists them in.
|
||||
|
||||
@@ -28,6 +28,21 @@ pub mod component {
|
||||
pub const STORED_ENCHANTMENTS: i32 = 45;
|
||||
pub const DYED_COLOR: i32 = 47;
|
||||
pub const MAP_ID: i32 = 48;
|
||||
pub const MAP_POST_PROCESSING: i32 = 50;
|
||||
pub const WRITABLE_BOOK_CONTENT: i32 = 56;
|
||||
pub const WRITTEN_BOOK_CONTENT: i32 = 57;
|
||||
}
|
||||
|
||||
/// A written book's content (`WrittenBookContent.STREAM_CODEC`): the
|
||||
/// filtered variants of the title and pages are read and dropped.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WrittenBook {
|
||||
pub title: String,
|
||||
pub author: String,
|
||||
pub generation: i32,
|
||||
/// Each page's text component.
|
||||
pub pages: Vec<Tag>,
|
||||
pub resolved: bool,
|
||||
}
|
||||
|
||||
/// The value of one patched data component. Components whose stream codec
|
||||
@@ -52,13 +67,49 @@ pub enum Component {
|
||||
hide: bool,
|
||||
hidden: Vec<i32>,
|
||||
},
|
||||
/// `WritableBookContent`: the pages (raw text).
|
||||
WritableBook(Vec<String>),
|
||||
WrittenBook(WrittenBook),
|
||||
}
|
||||
|
||||
/// `Filterable.streamCodec`: the raw value, then an optional filtered one
|
||||
/// (dropped).
|
||||
fn filterable<T>(r: &mut Reader, value: impl Fn(&mut Reader) -> Result<T>) -> Result<T> {
|
||||
let raw = value(r)?;
|
||||
if r.bool()? {
|
||||
value(r)?;
|
||||
}
|
||||
Ok(raw)
|
||||
}
|
||||
impl Component {
|
||||
fn read(kind: i32, r: &mut Reader) -> Result<Self> {
|
||||
use component::*;
|
||||
Ok(match kind {
|
||||
MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID => {
|
||||
Self::Int(r.varint()?)
|
||||
MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID
|
||||
| MAP_POST_PROCESSING => Self::Int(r.varint()?),
|
||||
WRITABLE_BOOK_CONTENT => {
|
||||
let n = r.count(100)?;
|
||||
Self::WritableBook(
|
||||
(0..n)
|
||||
.map(|_| filterable(r, |r| r.string(1024)))
|
||||
.collect::<Result<_>>()?,
|
||||
)
|
||||
}
|
||||
WRITTEN_BOOK_CONTENT => {
|
||||
let title = filterable(r, |r| r.string(32))?;
|
||||
let author = r.string(32767)?;
|
||||
let generation = r.varint()?;
|
||||
let n = r.count(r.remaining())?;
|
||||
let pages = (0..n)
|
||||
.map(|_| filterable(r, |r| r.nbt()))
|
||||
.collect::<Result<_>>()?;
|
||||
Self::WrittenBook(WrittenBook {
|
||||
title,
|
||||
author,
|
||||
generation,
|
||||
pages,
|
||||
resolved: r.bool()?,
|
||||
})
|
||||
}
|
||||
DYED_COLOR => Self::Int(r.i32()?),
|
||||
UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit,
|
||||
@@ -144,6 +195,25 @@ impl Component {
|
||||
w.varint(hidden.len() as i32);
|
||||
hidden.iter().for_each(|h| w.varint(*h));
|
||||
}
|
||||
Self::WritableBook(pages) => {
|
||||
w.varint(pages.len() as i32);
|
||||
for page in pages {
|
||||
w.string(page);
|
||||
w.bool(false);
|
||||
}
|
||||
}
|
||||
Self::WrittenBook(b) => {
|
||||
w.string(&b.title);
|
||||
w.bool(false);
|
||||
w.string(&b.author);
|
||||
w.varint(b.generation);
|
||||
w.varint(b.pages.len() as i32);
|
||||
for page in &b.pages {
|
||||
w.nbt(page);
|
||||
w.bool(false);
|
||||
}
|
||||
w.bool(b.resolved);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -349,12 +419,43 @@ mod tests {
|
||||
Component::Lore(vec![literal("a"), literal("b")]),
|
||||
));
|
||||
sword.removed.push(component::REPAIR_COST);
|
||||
let mut book = Stack::new(1100, 1);
|
||||
book.added.push((
|
||||
component::WRITTEN_BOOK_CONTENT,
|
||||
Component::WrittenBook(WrittenBook {
|
||||
title: "Notes".into(),
|
||||
author: "Guest".into(),
|
||||
generation: 1,
|
||||
pages: vec![literal("one"), literal("two")],
|
||||
resolved: true,
|
||||
}),
|
||||
));
|
||||
book.added
|
||||
.push((component::MAP_POST_PROCESSING, Component::Int(1)));
|
||||
round::<Option<Stack>, Slot>(Some(book));
|
||||
let mut quill = Stack::new(1099, 1);
|
||||
quill.added.push((
|
||||
component::WRITABLE_BOOK_CONTENT,
|
||||
Component::WritableBook(vec!["a".into(), String::new()]),
|
||||
));
|
||||
round::<Option<Stack>, Slot>(Some(quill));
|
||||
assert_eq!(sword.damage(), 17);
|
||||
round::<Option<Stack>, Slot>(Some(sword.clone()));
|
||||
round::<Option<Hashed>, HashedSlot>(Some(Hashed::of(&sword)));
|
||||
round::<Option<Hashed>, HashedSlot>(None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtered_book_pages_are_read_and_dropped() {
|
||||
// A writable book with one page "hi" and its filtered "**".
|
||||
let bytes = [1, 7, 1, 0, 56, 1, 2, b'h', b'i', 1, 2, b'*', b'*'];
|
||||
let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
stack.component(component::WRITABLE_BOOK_CONTENT),
|
||||
Some(&Component::WritableBook(vec!["hi".into()]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_stack_is_a_zero_count() {
|
||||
let mut w = Writer::new();
|
||||
|
||||
@@ -1712,6 +1712,25 @@ packet!(
|
||||
}
|
||||
);
|
||||
packet!(SelectTrade { item: i32 => VarInt });
|
||||
packet!(
|
||||
/// ServerboundContainerButtonClickPacket: `AbstractContainerMenu.clickMenuButton`
|
||||
/// (the loom's patterns, the stonecutter's recipes, the enchanting table's offers).
|
||||
ContainerButtonClick { container: i32 => VarInt, button: i32 => VarInt }
|
||||
);
|
||||
packet!(
|
||||
/// ServerboundContainerSlotStateChangedPacket: the crafter's slot toggle
|
||||
/// (`CrafterBlockEntity.setSlotState`).
|
||||
ContainerSlotStateChanged { slot: i32 => VarInt, container: i32 => VarInt, enabled: bool => Bool }
|
||||
);
|
||||
packet!(
|
||||
/// ServerboundRenameItemPacket: `AnvilMenu.setItemName`.
|
||||
RenameItem { name: String => Str }
|
||||
);
|
||||
packet!(
|
||||
/// ServerboundSetBeaconPacket: `BeaconMenu.updateEffects`, each power an
|
||||
/// optional `mob_effect` id.
|
||||
SetBeacon { primary: Option<i32> => Opt<VarInt>, secondary: Option<i32> => Opt<VarInt> }
|
||||
);
|
||||
packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool });
|
||||
packet!(
|
||||
/// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision.
|
||||
@@ -1777,6 +1796,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
|
||||
ClientInformation(ClientInformation) = CLIENT_INFORMATION,
|
||||
ClientTickEnd(Empty) = CLIENT_TICK_END,
|
||||
ConfigurationAcknowledged(Empty) = CONFIGURATION_ACKNOWLEDGED,
|
||||
ContainerButtonClick(ContainerButtonClick) = CONTAINER_BUTTON_CLICK,
|
||||
ContainerClick(ContainerClick) = CONTAINER_CLICK,
|
||||
ContainerClose(ContainerClose) = CONTAINER_CLOSE,
|
||||
CustomPayload(CustomPayload) = CUSTOM_PAYLOAD,
|
||||
@@ -1794,9 +1814,12 @@ packet_enum!(Serverbound, crate::ids::play::serverbound {
|
||||
PlayerInput(PlayerInput) = PLAYER_INPUT,
|
||||
PlayerLoaded(Empty) = PLAYER_LOADED,
|
||||
Pong(Ping) = PONG,
|
||||
RenameItem(RenameItem) = RENAME_ITEM,
|
||||
ContainerSlotStateChanged(ContainerSlotStateChanged) = CONTAINER_SLOT_STATE_CHANGED,
|
||||
Punch(Empty) = PUNCH,
|
||||
ResourcePack(ResourcePackResponse) = RESOURCE_PACK,
|
||||
SelectTrade(SelectTrade) = SELECT_TRADE,
|
||||
SetBeacon(SetBeacon) = SET_BEACON,
|
||||
SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM,
|
||||
SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT,
|
||||
UseItem(UseItem) = USE_ITEM,
|
||||
@@ -2374,6 +2397,34 @@ mod tests {
|
||||
Serverbound::encode,
|
||||
Serverbound::decode,
|
||||
);
|
||||
// CONTAINER_ID and the button, both VarInts.
|
||||
let button = Serverbound::ContainerButtonClick(ContainerButtonClick {
|
||||
container: 3,
|
||||
button: 200,
|
||||
});
|
||||
assert_eq!(&button.encode()[1..], &[3, 0xC8, 1]);
|
||||
round_trip(button, Serverbound::encode, Serverbound::decode);
|
||||
// The name, a UTF-8 string with its VarInt length.
|
||||
let rename = Serverbound::RenameItem(RenameItem {
|
||||
name: "Blade".into(),
|
||||
});
|
||||
assert_eq!(&rename.encode()[1..], &[5, b'B', b'l', b'a', b'd', b'e']);
|
||||
round_trip(rename, Serverbound::encode, Serverbound::decode);
|
||||
// The slot, the container id (VarInts), then the new state.
|
||||
let toggle = Serverbound::ContainerSlotStateChanged(ContainerSlotStateChanged {
|
||||
slot: 4,
|
||||
container: 2,
|
||||
enabled: false,
|
||||
});
|
||||
assert_eq!(&toggle.encode()[1..], &[4, 2, 0]);
|
||||
round_trip(toggle, Serverbound::encode, Serverbound::decode);
|
||||
// Two optional mob effect ids: a presence byte, then the VarInt.
|
||||
let beacon = Serverbound::SetBeacon(SetBeacon {
|
||||
primary: Some(2),
|
||||
secondary: None,
|
||||
});
|
||||
assert_eq!(&beacon.encode()[1..], &[1, 2, 0]);
|
||||
round_trip(beacon, Serverbound::encode, Serverbound::decode);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -39,6 +39,8 @@ public final class VanillaMenuOracle {
|
||||
static final List<String> equips = new ArrayList<>();
|
||||
/** The block entity behind a "crafter_be" menu (slot state packets go to it). */
|
||||
static net.minecraft.world.level.block.entity.CrafterBlockEntity crafter;
|
||||
/** The block entity behind a "lectern" menu. */
|
||||
static net.minecraft.world.level.block.entity.LecternBlockEntity lectern;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T make(Class<T> type) {
|
||||
@@ -87,8 +89,22 @@ public final class VanillaMenuOracle {
|
||||
// BlockEntity.setChanged of the "*_be" furnaces: no chunks here.
|
||||
@Override public void blockEntityChanged(BlockPos pos) { }
|
||||
@Override public void updateNeighbourForOutputSignal(BlockPos pos, net.minecraft.world.level.block.Block block) { }
|
||||
// The case's maps (MapItem.getSavedData) and the ones the cartography table makes.
|
||||
@Override public net.minecraft.world.level.saveddata.maps.MapItemSavedData getMapData(net.minecraft.world.level.saveddata.maps.MapId id) { return maps.get(id.id()); }
|
||||
@Override public net.minecraft.world.level.saveddata.maps.MapId getFreeMapId() { return new net.minecraft.world.level.saveddata.maps.MapId(nextMap++); }
|
||||
@Override public void setMapData(net.minecraft.world.level.saveddata.maps.MapId id, net.minecraft.world.level.saveddata.maps.MapItemSavedData data) { maps.put(id.id(), data); }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
// LecternBlock.signalPageChange and resetBookState: no chunks or ticks here.
|
||||
@Override public boolean setBlock(BlockPos pos, net.minecraft.world.level.block.state.BlockState state, int flags, int recursion) { return true; }
|
||||
@Override public void scheduleTick(BlockPos pos, net.minecraft.world.level.block.Block block, int delay) { }
|
||||
@Override public void updateNeighborsAt(BlockPos pos, net.minecraft.world.level.block.Block block, net.minecraft.world.level.redstone.Orientation o) { }
|
||||
@Override public void playSound(net.minecraft.world.entity.Entity e, BlockPos pos, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) { }
|
||||
}
|
||||
|
||||
/** The maps of the case's level, by id, and the next free id. */
|
||||
static final Map<Integer, net.minecraft.world.level.saveddata.maps.MapItemSavedData> maps = new HashMap<>();
|
||||
static int nextMap;
|
||||
|
||||
static final class FakePlayer extends ServerPlayer {
|
||||
World world;
|
||||
boolean creative;
|
||||
@@ -178,10 +194,42 @@ public final class VanillaMenuOracle {
|
||||
}
|
||||
}
|
||||
case "loom" -> new LoomMenu(0, inv);
|
||||
case "stonecutter" -> new StonecutterMenu(0, inv);
|
||||
case "grindstone" -> new GrindstoneMenu(0, inv);
|
||||
case "anvil" -> new AnvilMenu(0, inv);
|
||||
case "smithing" -> new SmithingMenu(0, inv);
|
||||
case "enchanting" -> new EnchantmentMenu(0, inv);
|
||||
case "beacon" -> new BeaconMenu(0, inv);
|
||||
// Over the level (its maps), as the server's menu is.
|
||||
case "cartography" -> new CartographyTableMenu(0, inv, access);
|
||||
case "lectern" -> {
|
||||
// The server's menu: the block entity's bookAccess and dataAccess.
|
||||
lectern = new net.minecraft.world.level.block.entity.LecternBlockEntity(BlockPos.ZERO,
|
||||
net.minecraft.world.level.block.Blocks.LECTERN.defaultBlockState());
|
||||
lectern.setLevel(player.world);
|
||||
try {
|
||||
var type = net.minecraft.world.level.block.entity.LecternBlockEntity.class;
|
||||
Field book = type.getDeclaredField("bookAccess");
|
||||
Field data = type.getDeclaredField("dataAccess");
|
||||
book.setAccessible(true);
|
||||
data.setAccessible(true);
|
||||
yield new LecternMenu(0, (Container) book.get(lectern), (ContainerData) data.get(lectern));
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalArgumentException(kind);
|
||||
};
|
||||
}
|
||||
|
||||
/** A SET_BEACON power: a mob effect's name, or null for none. */
|
||||
static Optional<net.minecraft.core.Holder<net.minecraft.world.effect.MobEffect>> effect(JsonElement name) {
|
||||
if (name.isJsonNull()) return Optional.empty();
|
||||
return net.minecraft.core.registries.BuiltInRegistries.MOB_EFFECT
|
||||
.get(net.minecraft.resources.Identifier.parse(name.getAsString()))
|
||||
.map(h -> (net.minecraft.core.Holder<net.minecraft.world.effect.MobEffect>) h);
|
||||
}
|
||||
|
||||
static String state(AbstractContainerMenu menu, Inventory inv) throws Exception {
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < menu.slots.size(); i++) {
|
||||
@@ -199,6 +247,12 @@ public final class VanillaMenuOracle {
|
||||
|
||||
/** {@link #state} and what was equipped: the menu_click harness's line (place_recipe prints {@code state}). */
|
||||
static String clickState(AbstractContainerMenu menu, Inventory inv) throws Exception {
|
||||
if (menu instanceof LecternMenu) {
|
||||
// No inventory slots: the inventory Take Book fills.
|
||||
StringBuilder items = new StringBuilder();
|
||||
for (int i = 0; i < 36; i++) items.append(' ').append(ParityData.canon(inv.getItem(i)));
|
||||
return state(menu, inv) + " | " + String.join(";", equips) + " | inv" + items;
|
||||
}
|
||||
return state(menu, inv) + " | " + String.join(";", equips);
|
||||
}
|
||||
|
||||
@@ -225,6 +279,25 @@ public final class VanillaMenuOracle {
|
||||
player.advancements = make(net.minecraft.server.PlayerAdvancements.class);
|
||||
set(player.advancements, net.minecraft.server.PlayerAdvancements.class, "activeTriggers", new java.util.IdentityHashMap<>());
|
||||
set(player, ServerPlayer.class, "connection", make(Connection.class));
|
||||
// AnvilMenu.onTake filters a new name; the anvil's result needs the levels.
|
||||
set(player, ServerPlayer.class, "textFilter", net.minecraft.server.network.TextFilter.DUMMY);
|
||||
// EnchantmentMenu.clickMenuButton names the player on an invalid button.
|
||||
set(player, Player.class, "gameProfile", new com.mojang.authlib.GameProfile(new java.util.UUID(0, 1), "Oracle"));
|
||||
player.experienceLevel = f.has("levels") ? f.get("levels").getAsInt() : 0;
|
||||
maps.clear();
|
||||
nextMap = 1000;
|
||||
lectern = null;
|
||||
// LecternMenu's Take Book asks Player.mayBuild.
|
||||
set(player, Player.class, "abilities", new net.minecraft.world.entity.player.Abilities());
|
||||
if (f.has("maps")) {
|
||||
// [id, scale, locked] each.
|
||||
for (var m : f.getAsJsonArray("maps")) {
|
||||
var a = m.getAsJsonArray();
|
||||
var data = net.minecraft.world.level.saveddata.maps.MapItemSavedData.createFresh(0, 0,
|
||||
(byte) a.get(1).getAsInt(), false, false, net.minecraft.world.level.Level.OVERWORLD);
|
||||
maps.put(a.get(0).getAsInt(), a.get(2).getAsBoolean() ? data.locked() : data);
|
||||
}
|
||||
}
|
||||
var inv = new Inventory(player, new EntityEquipment());
|
||||
player.inv = inv;
|
||||
AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv);
|
||||
@@ -233,6 +306,19 @@ public final class VanillaMenuOracle {
|
||||
var slotsJson = f.getAsJsonArray("slots");
|
||||
for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString()));
|
||||
menu.setCarried(ParityData.stack(f.get("carried").getAsString()));
|
||||
if (lectern != null && menu instanceof LecternMenu) {
|
||||
// LecternBlockEntity.setBook without resolving the book: its slot can't set it.
|
||||
var type = net.minecraft.world.level.block.entity.LecternBlockEntity.class;
|
||||
ItemStack book = ParityData.stack(slotsJson.get(0).getAsString());
|
||||
set(lectern, type, "book", book);
|
||||
var count = type.getDeclaredMethod("getPageCount", ItemStack.class);
|
||||
count.setAccessible(true);
|
||||
set(lectern, type, "pageCount", count.invoke(null, book));
|
||||
}
|
||||
if (f.has("inventory")) {
|
||||
var items = f.getAsJsonArray("inventory");
|
||||
for (int i = 0; i < items.size(); i++) inv.setItem(i, ParityData.stack(items.get(i).getAsString()));
|
||||
}
|
||||
// The slot listener of the block crafter's menu refreshes the result.
|
||||
if (f.get("menu").getAsString().equals("crafter_be")) menu.broadcastChanges();
|
||||
var dataJson = f.getAsJsonArray("data");
|
||||
@@ -251,6 +337,18 @@ public final class VanillaMenuOracle {
|
||||
out.println(clickState(menu, inv));
|
||||
continue;
|
||||
}
|
||||
if (kind.equals("RENAME")) {
|
||||
// ServerGamePacketListenerImpl.handleRenameItem: AnvilMenu.setItemName
|
||||
if (menu instanceof AnvilMenu anvil) anvil.setItemName(op.get(3).getAsString());
|
||||
out.println(clickState(menu, inv));
|
||||
continue;
|
||||
}
|
||||
if (kind.equals("SET_BEACON")) {
|
||||
// ServerGamePacketListenerImpl.handleSetBeaconPacket: BeaconMenu.updateEffects
|
||||
if (menu instanceof BeaconMenu beacon) beacon.updateEffects(effect(op.get(3)), effect(op.get(4)));
|
||||
out.println(clickState(menu, inv));
|
||||
continue;
|
||||
}
|
||||
if (kind.equals("SLOT_STATE")) {
|
||||
// handleContainerSlotStateChanged: CrafterBlockEntity.setSlotState
|
||||
if (slot >= 0 && slot < 9) crafter.setSlotState(slot, button == 1);
|
||||
|
||||
+432
-1
@@ -36,6 +36,28 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- brewing: a brewing stand opens on the guest's screen; blaze powder, nether wart and a bottle the
|
||||
guest shift-clicks go to the fuel, ingredient and bottle slots, and the stand's fuel shows
|
||||
(#848);
|
||||
- loom: a loom opens on the guest's screen; the banner and dye the guest shift-clicks go to their
|
||||
slots, a pattern button the guest clicks makes the server's result, and the guest takes the
|
||||
patterned banner (#868);
|
||||
- stonecutter: a stonecutter opens on the guest's screen with the recipes of the stone the guest puts
|
||||
in; the guest picks the slab and shift-clicks the result, and the server has cut every
|
||||
stone into slabs (#868);
|
||||
- grindstone: a grindstone opens on the guest's screen; the enchanted sword the guest shift-clicks in
|
||||
shows the server's result, and the guest takes it with only its curse left and the
|
||||
experience orbs the server awards (#868);
|
||||
- anvil: an anvil opens on the guest's screen; the guest repairs a sword with iron ingots and
|
||||
renames it (ServerboundRenameItemPacket), takes it for the server's level cost, and the
|
||||
server has the repaired, renamed sword (#868);
|
||||
- enchanting: an enchanting table opens on the guest's screen with the server's offers for the
|
||||
sword the guest puts in; the guest clicks the first offer and the server enchants the
|
||||
sword for a level and a lapis, and counts it in the guest's enchant_item stat (#868);
|
||||
- smithing: a smithing table opens on the guest's screen; the guest upgrades a diamond sword to
|
||||
netherite and the server has it (#868);
|
||||
- lectern: a lectern's written book opens on the guest's screen; the guest turns its pages
|
||||
(ContainerButtonClick) and the server's lectern follows, then the guest takes the book
|
||||
and the server has it in the guest's inventory (#868);
|
||||
- cartography: a cartography table opens on the guest's screen; the guest puts in a map the host
|
||||
made and paper, takes the zoomed-out map, and the server has a new map for it (#868);
|
||||
- feedback: the guest's command feedback names the guest and shows the numbers;
|
||||
- chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the
|
||||
server thread the host window's too;
|
||||
@@ -133,7 +155,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
GUEST_NAME = 'Guest'
|
||||
# The host plays single player on its server thread (--server-thread).
|
||||
SERVER_THREAD = False
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight']
|
||||
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight']
|
||||
|
||||
|
||||
class Game:
|
||||
@@ -917,6 +939,405 @@ def check_brewing(host, guest, out):
|
||||
return seen
|
||||
|
||||
|
||||
def open_station(guest, block, out, label):
|
||||
"""Place `block` two blocks south of the guest and open it: the station's position."""
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
at = (x, y, z + 2)
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}')
|
||||
guest.wait(10)
|
||||
guest.raw('interact', *at)
|
||||
guest.raw('wait-for', 'screen', 'station', '--timeout', 10)
|
||||
guest.wait(10)
|
||||
guest.shot(out, label)
|
||||
return at
|
||||
|
||||
|
||||
def station_slots(guest):
|
||||
"""The open station's stacks: input slots 600 and up, the result at 650."""
|
||||
menu = guest.raw('menu')
|
||||
return {s['slot']: (s['stack']['item'], s['stack']['count']) for s in menu['slots'] if s['slot'] >= 600}
|
||||
|
||||
|
||||
def close_station(guest, at):
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(10)
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
|
||||
|
||||
def check_loom(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
for item in ('white_banner', 'red_dye'):
|
||||
guest('command', command=f'give @s minecraft:{item}')
|
||||
at = open_station(guest, 'loom', out, 'loom')
|
||||
# LoomMenu.quickMoveStack: a banner to the banner slot, a dye to the dye slot.
|
||||
for item in ('white_banner', 'red_dye'):
|
||||
guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift')
|
||||
guest.wait(5)
|
||||
loaded = station_slots(guest)
|
||||
# LoomScreen's first pattern button (clickMenuButton 0): the server makes the result.
|
||||
guest.raw('click-gui', 67, 20)
|
||||
guest.wait(10)
|
||||
made = station_slots(guest).get(650)
|
||||
guest.shot(out, 'loom-pattern')
|
||||
guest.raw('click-slot', 650, 'shift')
|
||||
guest.wait(10)
|
||||
left = station_slots(guest)
|
||||
close_station(guest, at)
|
||||
# The server's copy of the banner the guest took has the red layer.
|
||||
since = guest.raw('events')['last']
|
||||
guest('command', command='data get entity @s Inventory[{id:"minecraft:white_banner"}].components')
|
||||
layer = guest.raw('wait-for', 'chat', 'color: "red"', '--timeout', 10, '--since', since).get('ok')
|
||||
counts = guest('inventory')['counts']
|
||||
seen = {'loaded': loaded, 'made': made, 'left': left, 'layer': layer, 'counts': counts}
|
||||
want = {'loaded': {600: ('minecraft:white_banner', 1), 601: ('minecraft:red_dye', 1)},
|
||||
'made': ('minecraft:white_banner', 1), 'left': {}, 'layer': True,
|
||||
'counts': {'minecraft:white_banner': 1}}
|
||||
assert seen == want, f'the loom on the guest: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def own_reply(event):
|
||||
"""A chat event that answers the guest's own command. On the server thread the guest also gets
|
||||
its own command's `[Guest: ...]` operator broadcast, a moment later, which an answer to the next
|
||||
command must not be taken for."""
|
||||
return event.get('event') == 'chat' and not event.get('text', '').startswith(f'[{GUEST_NAME}: ')
|
||||
|
||||
|
||||
def server_count(guest, item):
|
||||
"""How many of `item` the server says the guest has (`clear` with a count of 0 only counts)."""
|
||||
since = guest.raw('events')['last']
|
||||
guest('command', command=f'clear @s minecraft:{item} 0')
|
||||
for n in range(0, 65):
|
||||
reply = guest.raw('events', '--since', since)
|
||||
lines = [e.get('text', '') for e in reply['events'] if own_reply(e)]
|
||||
for line in lines:
|
||||
if 'matching item' in line or 'No items were found' in line:
|
||||
return 0 if 'No items' in line else int(line.split('Found ')[1].split(' ')[0])
|
||||
guest.wait(2)
|
||||
raise Failed(f'no answer to clear for {item}')
|
||||
|
||||
|
||||
def check_stonecutter(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='give @s minecraft:stone 3')
|
||||
at = open_station(guest, 'stonecutter', out, 'stonecutter')
|
||||
# StonecutterMenu.quickMoveStack: stone has recipes, so it goes to the input.
|
||||
guest.raw('click-slot', hotbar_slot(guest, 'minecraft:stone'), 'shift')
|
||||
guest.wait(10)
|
||||
recipes = guest.raw('menu')['info']['recipes']
|
||||
index = recipes.index('minecraft:stone_slab_from_stone_stonecutting')
|
||||
# StonecutterScreen's recipe grid: four columns of 16x18 cells from (52, 14).
|
||||
guest.raw('click-gui', 52 + index % 4 * 16 + 8, 14 + index // 4 * 18 + 9)
|
||||
guest.wait(10)
|
||||
picked = (guest.raw('menu')['info']['selected'], station_slots(guest).get(650))
|
||||
guest.shot(out, 'stonecutter-recipe')
|
||||
# A shift-click on the result cuts while there is stone (doClick repeats quickMoveStack).
|
||||
guest.raw('click-slot', 650, 'shift')
|
||||
guest.wait(10)
|
||||
left = station_slots(guest)
|
||||
close_station(guest, at)
|
||||
seen = {'picked': picked, 'left': left,
|
||||
'server': {item: server_count(guest, item) for item in ('stone_slab', 'stone')}}
|
||||
want = {'picked': (index, ('minecraft:stone_slab', 2)), 'left': {},
|
||||
'server': {'stone_slab': 6, 'stone': 0}}
|
||||
assert seen == want, f'the stonecutter on the guest: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def server_reply(guest, command, *needles):
|
||||
"""The first chat line holding every needle after the guest runs `command`."""
|
||||
since = guest.raw('events')['last']
|
||||
guest('command', command=command)
|
||||
for _ in range(0, 65):
|
||||
reply = guest.raw('events', '--since', since)
|
||||
for e in reply['events']:
|
||||
line = e.get('text', '')
|
||||
if own_reply(e) and all(n in line for n in needles):
|
||||
return line
|
||||
guest.wait(2)
|
||||
raise Failed(f'no answer to {command}')
|
||||
|
||||
|
||||
def check_grindstone(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='xp set @s 0 levels')
|
||||
guest('command', command='xp set @s 0 points')
|
||||
guest('command', command='give @s minecraft:iron_sword[minecraft:enchantments={"minecraft:sharpness":3,'
|
||||
'"minecraft:vanishing_curse":1},minecraft:damage=100]')
|
||||
at = open_station(guest, 'grindstone', out, 'grindstone')
|
||||
# GrindstoneMenu.quickMoveStack: with both inputs empty, into the first.
|
||||
guest.raw('click-slot', hotbar_slot(guest, 'minecraft:iron_sword'), 'shift')
|
||||
guest.wait(10)
|
||||
loaded = station_slots(guest)
|
||||
guest.shot(out, 'grindstone-result')
|
||||
guest.raw('click-slot', 650, 'shift')
|
||||
# The orbs (sharpness III: 12 to 23 points) fly to the guest.
|
||||
guest.wait(60)
|
||||
left = station_slots(guest)
|
||||
close_station(guest, at)
|
||||
sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}].components',
|
||||
'minecraft:damage')
|
||||
# 16 points make exactly two levels and leave 0 points: count the levels too.
|
||||
xp = (server_reply(guest, 'xp query @s points', 'experience points')
|
||||
+ server_reply(guest, 'xp query @s levels', 'experience levels'))
|
||||
seen = {'loaded': loaded, 'left': left, 'curse kept': 'vanishing_curse' in sword,
|
||||
'sharpness gone': 'sharpness' not in sword,
|
||||
'damage': re.search(r'minecraft:damage"?: 100\b', sword) is not None,
|
||||
'xp': any(int(n) > 0 for n in re.findall(r'has (\d+) experience', xp))}
|
||||
want = {'loaded': {600: ('minecraft:iron_sword', 1), 650: ('minecraft:iron_sword', 1)}, 'left': {},
|
||||
'curse kept': True, 'sharpness gone': True, 'damage': True, 'xp': True}
|
||||
assert seen == want, f'the grindstone on the guest: {seen} ({sword!r}, {xp!r})'
|
||||
return seen
|
||||
|
||||
|
||||
def check_anvil(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='xp set @s 5 levels')
|
||||
guest('command', command='give @s minecraft:iron_sword[minecraft:damage=200]')
|
||||
guest('command', command='give @s minecraft:iron_ingot 3')
|
||||
at = open_station(guest, 'anvil', out, 'anvil')
|
||||
# ItemCombinerMenu.quickMoveStack: into the first input that takes it.
|
||||
for item in ('iron_sword', 'iron_ingot'):
|
||||
guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift')
|
||||
guest.wait(5)
|
||||
# The box shows "Iron Sword": erase it and type the new name.
|
||||
for _ in range(len('Iron Sword')):
|
||||
guest.raw('type-back')
|
||||
guest.raw('type', 'Blade')
|
||||
guest.wait(10)
|
||||
menu = guest.raw('menu')
|
||||
offered = (menu['info']['anvil_cost'], station_slots(guest).get(650))
|
||||
guest.shot(out, 'anvil-rename')
|
||||
guest.raw('click-slot', 650, 'shift')
|
||||
guest.wait(10)
|
||||
left = station_slots(guest)
|
||||
close_station(guest, at)
|
||||
sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}].components',
|
||||
'minecraft:damage')
|
||||
levels = server_reply(guest, 'xp query @s levels', 'experience levels')
|
||||
seen = {'offered': offered, 'left': left, 'name': 'Blade' in sword,
|
||||
'damage': re.search(r'minecraft:damage"?: 14\b', sword) is not None,
|
||||
'levels': int(re.search(r'has (\d+) experience', levels).group(1)),
|
||||
'ingots': server_count(guest, 'iron_ingot')}
|
||||
# Three ingots repair 62 each (a quarter of 250), plus the name: four levels.
|
||||
want = {'offered': (4, ('minecraft:iron_sword', 1)), 'left': {}, 'name': True, 'damage': True,
|
||||
'levels': 1, 'ingots': 0}
|
||||
assert seen == want, f'the anvil on the guest: {seen} ({sword!r})'
|
||||
return seen
|
||||
|
||||
|
||||
def check_smithing(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
for item in ('netherite_upgrade_smithing_template', 'diamond_sword', 'netherite_ingot'):
|
||||
guest('command', command=f'give @s minecraft:{item}')
|
||||
at = open_station(guest, 'smithing_table', out, 'smithing')
|
||||
# SmithingMenu.canMoveIntoInputSlots: each to the slot whose recipe test takes it.
|
||||
for item in ('netherite_upgrade_smithing_template', 'diamond_sword', 'netherite_ingot'):
|
||||
guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift')
|
||||
guest.wait(5)
|
||||
guest.wait(5)
|
||||
loaded = station_slots(guest)
|
||||
guest.shot(out, 'smithing-result')
|
||||
guest.raw('click-slot', 650, 'shift')
|
||||
guest.wait(10)
|
||||
left = station_slots(guest)
|
||||
close_station(guest, at)
|
||||
seen = {'loaded': loaded, 'left': left,
|
||||
'server': {item: server_count(guest, item) for item in ('netherite_sword', 'diamond_sword', 'netherite_ingot')}}
|
||||
want = {'loaded': {600: ('minecraft:netherite_upgrade_smithing_template', 1), 601: ('minecraft:diamond_sword', 1),
|
||||
602: ('minecraft:netherite_ingot', 1), 650: ('minecraft:netherite_sword', 1)},
|
||||
'left': {}, 'server': {'netherite_sword': 1, 'diamond_sword': 0, 'netherite_ingot': 0}}
|
||||
assert seen == want, f'the smithing table on the guest: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_enchanting(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='xp set @s 30 levels')
|
||||
guest('command', command='give @s minecraft:iron_sword')
|
||||
guest('command', command='give @s minecraft:lapis_lazuli 3')
|
||||
# EnchantmentMenu awards the enchant_item stat; a stat objective shows the guest's count.
|
||||
guest('command', command='scoreboard objectives add lanench minecraft.custom:minecraft.enchant_item')
|
||||
at = open_station(guest, 'enchanting_table', out, 'enchanting')
|
||||
# EnchantmentMenu.quickMoveStack: the sword to the item slot, the lapis to its own.
|
||||
for item in ('iron_sword', 'lapis_lazuli'):
|
||||
guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift')
|
||||
guest.wait(5)
|
||||
guest.wait(10)
|
||||
costs = guest.raw('menu')['info']['costs']
|
||||
guest.shot(out, 'enchanting-offers')
|
||||
# EnchantmentScreen's first offer button (clickMenuButton 0).
|
||||
guest.raw('click-gui', 110, 23)
|
||||
guest.wait(10)
|
||||
left = station_slots(guest)
|
||||
close_station(guest, at)
|
||||
sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}]', 'iron_sword')
|
||||
levels = server_reply(guest, 'xp query @s levels', 'experience levels')
|
||||
stat = server_reply(guest, 'scoreboard players get @s lanench', 'lanench')
|
||||
guest('command', command='scoreboard objectives remove lanench')
|
||||
seen = {'offered': costs[0] > 0, 'enchanted': 'minecraft:enchantments' in sword,
|
||||
'left': left.get(601), 'levels': int(re.search(r'has (\d+) experience', levels).group(1)),
|
||||
'lapis': server_count(guest, 'lapis_lazuli'), 'stat': ' has 1 ' in stat}
|
||||
want = {'offered': True, 'enchanted': True, 'left': ('minecraft:lapis_lazuli', 2), 'levels': 29, 'lapis': 2,
|
||||
'stat': True}
|
||||
assert seen == want, f'the enchanting table on the guest: {seen} ({costs}, {sword!r})'
|
||||
return seen
|
||||
|
||||
|
||||
def check_beacon(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='effect clear @s')
|
||||
guest('command', command='give @s minecraft:iron_ingot')
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
at = (x, y, z + 2)
|
||||
# A one-level pyramid under the beacon; its levels come with the first base check (80 ticks).
|
||||
guest('command', command=f'fill {x - 1} {y - 1} {z + 1} {x + 1} {y - 1} {z + 3} minecraft:iron_block')
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:beacon')
|
||||
guest.wait(100)
|
||||
guest.raw('interact', *at)
|
||||
guest.raw('wait-for', 'screen', 'station', '--timeout', 10)
|
||||
guest.wait(10)
|
||||
# BeaconMenu.quickMoveStack: the ingot to the payment slot.
|
||||
guest.raw('click-slot', hotbar_slot(guest, 'minecraft:iron_ingot'), 'shift')
|
||||
guest.wait(10)
|
||||
paid = station_slots(guest).get(600)
|
||||
# BeaconScreen (54 px wider, 27 to the left): Haste, the first level's second power, then Done,
|
||||
# which sends ServerboundSetBeaconPacket and closes the menu.
|
||||
guest.raw('click-gui', 77 - 27 + 11, 22 + 11)
|
||||
guest.wait(5)
|
||||
guest.shot(out, 'beacon')
|
||||
guest.raw('click-gui', 164 - 27 + 11, 107 + 11)
|
||||
guest.wait(10)
|
||||
screen = guest('state').get('screen')
|
||||
effects = []
|
||||
# BeaconBlockEntity.applyEffects runs every 80 ticks.
|
||||
for _ in range(12):
|
||||
guest.wait(20)
|
||||
effects = effect_ids(guest)
|
||||
if 'haste' in effects:
|
||||
break
|
||||
seen = {'paid': paid, 'haste': 'haste' in effects, 'ingots': server_count(guest, 'iron_ingot'),
|
||||
'screen': screen}
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
want = {'paid': ('minecraft:iron_ingot', 1), 'haste': True, 'ingots': 0, 'screen': 'playing'}
|
||||
assert seen == want, f'the beacon on the guest: {seen} ({effects})'
|
||||
return seen
|
||||
|
||||
|
||||
def check_crafter(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command='give @s minecraft:oak_planks 4')
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
at = (x, y, z + 2)
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:crafter')
|
||||
guest.wait(10)
|
||||
guest.raw('interact', *at)
|
||||
guest.raw('wait-for', 'screen', 'container', '--timeout', 10)
|
||||
guest.wait(10)
|
||||
# CrafterScreen.slotClicked: an empty-handed click disables the first slot
|
||||
# (ServerboundContainerSlotStateChangedPacket); the planks then skip it.
|
||||
guest.raw('click-slot', 300)
|
||||
guest.wait(5)
|
||||
guest.raw('click-slot', hotbar_slot(guest, 'minecraft:oak_planks'), 'shift')
|
||||
guest.wait(10)
|
||||
guest.shot(out, 'crafter')
|
||||
guest.raw('key', 'esc', 'tap')
|
||||
guest.wait(10)
|
||||
# Opening it again shows the server's crafter.
|
||||
items = open_container(guest, at, out, 'crafter-after')
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
seen = {'items': items[0] if isinstance(items, tuple) else items, 'planks': server_count(guest, 'oak_planks')}
|
||||
want = {'items': {1: 'minecraft:oak_planks'}, 'planks': 0}
|
||||
assert seen == want, f'the crafter on the guest: {seen}'
|
||||
return seen
|
||||
|
||||
|
||||
def check_lectern(host, guest, out):
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
at = (x, y, z + 2)
|
||||
book = ('{id:"minecraft:written_book",count:1,components:{"minecraft:written_book_content":'
|
||||
'{title:"Lan",author:"Host",pages:["one","two","three"]}}}')
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:lectern[has_book=true]{{Book:{book}}}')
|
||||
guest.wait(10)
|
||||
guest.raw('interact', *at)
|
||||
guest.raw('wait-for', 'screen', 'book', '--timeout', 10)
|
||||
guest.wait(10)
|
||||
opened = guest.raw('book')
|
||||
guest.shot(out, 'lectern')
|
||||
# LecternScreen's page arrows: ContainerButtonClick 2 (forward) and 1 (back); the server's
|
||||
# LecternMenu.setData clamps to the book's last page and sends the page back (data slot 0).
|
||||
for button in ('next', 'next', 'next', 'back'):
|
||||
guest.raw('book', button)
|
||||
guest.wait(5)
|
||||
guest.wait(10)
|
||||
turned = guest.raw('book')
|
||||
page = server_reply(guest, f'data get block {at[0]} {at[1]} {at[2]} Page', 'block data')
|
||||
guest.shot(out, 'lectern-page')
|
||||
# Take Book: ContainerButtonClick 3; the server empties the lectern and closes the menu.
|
||||
guest.raw('book', 'take')
|
||||
guest.wait(20)
|
||||
screen = guest('state').get('screen')
|
||||
held = server_count(guest, 'written_book')
|
||||
has_book = server_reply(guest, f'execute if block {at[0]} {at[1]} {at[2]} minecraft:lectern[has_book=false]',
|
||||
'Test passed')
|
||||
guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air')
|
||||
seen = {'opened': (opened.get('page'), opened.get('pages')), 'turned': turned.get('page'),
|
||||
'server page': int(re.search(r'(-?\d+)\s*$', page).group(1)), 'screen': screen, 'held': held,
|
||||
'emptied': 'Test passed' in has_book}
|
||||
want = {'opened': (0, 3), 'turned': 1, 'server page': 1, 'screen': 'playing', 'held': 1, 'emptied': True}
|
||||
assert seen == want, f'the lectern on the guest: {seen} ({page!r})'
|
||||
return seen
|
||||
|
||||
|
||||
def check_cartography(host, guest, out):
|
||||
# The host makes a map (EmptyMapItem.use), the guest gets a copy of it.
|
||||
host('command', command='clear @s')
|
||||
host('command', command='item replace entity @s weapon.mainhand with minecraft:map')
|
||||
host.wait(5)
|
||||
host.raw('use-item')
|
||||
host.wait(20)
|
||||
made = server_reply(host, 'data get entity @s Inventory[{id:"minecraft:filled_map"}].components', 'map_id')
|
||||
map_id = int(re.search(r'map_id"?: (\d+)', made).group(1))
|
||||
host('command', command='clear @s')
|
||||
guest('command', command='gamemode survival')
|
||||
guest('command', command='clear @s')
|
||||
guest('command', command=f'give @s minecraft:filled_map[minecraft:map_id={map_id}]')
|
||||
guest('command', command='give @s minecraft:paper')
|
||||
at = open_station(guest, 'cartography_table', out, 'cartography')
|
||||
# CartographyTableMenu.quickMoveStack: a map with an id to the map slot, paper to the other.
|
||||
for item in ('filled_map', 'paper'):
|
||||
guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift')
|
||||
guest.wait(5)
|
||||
guest.wait(10)
|
||||
loaded = station_slots(guest)
|
||||
guest.shot(out, 'cartography-result')
|
||||
# The result's onTake uses the map and the paper; MapItem.onCraftedPostProcess gives the zoomed
|
||||
# out map a new id on the server.
|
||||
guest.raw('click-slot', 650, 'shift')
|
||||
guest.wait(10)
|
||||
left = station_slots(guest)
|
||||
close_station(guest, at)
|
||||
taken = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:filled_map"}].components', 'map_id')
|
||||
new_id = int(re.search(r'map_id"?: (\d+)', taken).group(1))
|
||||
seen = {'loaded': loaded, 'left': left, 'new map': new_id != map_id,
|
||||
'server': {item: server_count(guest, item) for item in ('filled_map', 'paper')}}
|
||||
want = {'loaded': {600: ('minecraft:filled_map', 1), 601: ('minecraft:paper', 1),
|
||||
650: ('minecraft:filled_map', 1)},
|
||||
'left': {}, 'new map': True, 'server': {'filled_map': 1, 'paper': 0}}
|
||||
assert seen == want, f'the cartography table on the guest: {seen} ({made!r}, {taken!r})'
|
||||
return seen
|
||||
|
||||
|
||||
def slot_point(game, slot):
|
||||
"""The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N)."""
|
||||
for w in game.raw('ui')['widgets']:
|
||||
@@ -2152,6 +2573,16 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
|
||||
'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat,
|
||||
'machines': check_machines,
|
||||
'brewing': check_brewing,
|
||||
'loom': check_loom,
|
||||
'stonecutter': check_stonecutter,
|
||||
'grindstone': check_grindstone,
|
||||
'anvil': check_anvil,
|
||||
'smithing': check_smithing,
|
||||
'enchanting': check_enchanting,
|
||||
'beacon': check_beacon,
|
||||
'crafter': check_crafter,
|
||||
'lectern': check_lectern,
|
||||
'cartography': check_cartography,
|
||||
'hurt': check_hurt,
|
||||
'commands': check_commands,
|
||||
'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls,
|
||||
|
||||
@@ -10,7 +10,17 @@ click: QUICK_MOVE on every slot of the clicked slot's container holding the
|
||||
item the first click moved) over the player inventory,
|
||||
crafting table, chests, hopper, dispenser, shulker box, the furnaces, the
|
||||
brewing stand, the crafter (the client's menu, and the server's over the block
|
||||
entity with slot state packets), the loom (with its pattern buttons) and the
|
||||
entity with slot state packets), the loom (with its pattern buttons), the
|
||||
stonecutter (with its recipe buttons), the grindstone (enchanted, damaged and
|
||||
cursed tools and books), the anvil (repairs, enchantment merges and renames,
|
||||
with the player's levels), the smithing table (upgrades and trims), the
|
||||
enchanting table (its button checks against the costs, lapis and levels), the
|
||||
beacon (its payment slot and ServerboundSetBeaconPacket against the pyramid's
|
||||
levels), the
|
||||
cartography table (over a level with locked, scaled and missing maps: its
|
||||
results, and the scaled and locked copies a take makes), the lectern (over the
|
||||
block entity: its page buttons, clamped to the book's pages, and Take Book,
|
||||
with the inventory compared too) and the
|
||||
server's furnace menus over their block entities (`*_be`: a new input restarts
|
||||
cooking, other clicks keep its progress). After
|
||||
every click the slots, carried stack, data slots and drops are compared.
|
||||
@@ -26,8 +36,9 @@ except ImportError:
|
||||
|
||||
MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81,
|
||||
'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46,
|
||||
'crafter_be': 46, 'loom': 40, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39}
|
||||
'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'enchanting': 38, 'beacon': 37, 'cartography': 39, 'lectern': 1, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39}
|
||||
DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1,
|
||||
'stonecutter': 1, 'enchanting': 10, 'beacon': 3, 'lectern': 1,
|
||||
'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4}
|
||||
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
|
||||
'blue', 'brown', 'green', 'red', 'black']
|
||||
@@ -40,6 +51,27 @@ COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_i
|
||||
'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling',
|
||||
'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest', 'glass_bottle', 'nether_wart', 'blaze_powder',
|
||||
'redstone', 'gunpowder', 'sugar', 'potion', 'splash_potion', 'lingering_potion', 'fermented_spider_eye', 'dragon_breath']
|
||||
# Stonecutter inputs (several recipes each), and a block it doesn't cut.
|
||||
CUTTABLE = ['stone', 'cobblestone', 'andesite', 'granite', 'copper_block', 'sandstone', 'quartz_block', 'deepslate',
|
||||
'stone_bricks', 'oak_planks']
|
||||
# Grindstone inputs: tools and armor, books, and their enchantments (curses too).
|
||||
GRINDABLE = ['iron_sword', 'diamond_pickaxe', 'bow', 'iron_helmet', 'elytra', 'shield', 'fishing_rod', 'trident']
|
||||
# Beacon powers (BEACON_EFFECTS by level, and one no level gives) and payments.
|
||||
POWERS = ['speed', 'haste', 'resistance', 'jump_boost', 'strength', 'regeneration', 'night_vision']
|
||||
PAYMENTS = ['iron_ingot', 'gold_ingot', 'emerald', 'diamond', 'netherite_ingot']
|
||||
ENCHANTS = ['sharpness', 'unbreaking', 'mending', 'efficiency', 'protection', 'power', 'looting', 'fortune',
|
||||
'binding_curse', 'vanishing_curse']
|
||||
|
||||
|
||||
# Anvil renames (ServerboundRenameItemPacket): blank, too long, a section sign, an item's own name.
|
||||
NAMES = ['', ' ', 'Blade', 'Iron Sword', 'Diamond Pickaxe', 'Enchanted Book', '\u00a7cRed', 'x' * 50, 'x' * 51]
|
||||
# Smithing inputs: templates, bases and additions (trim materials and netherite).
|
||||
TEMPLATES = ['netherite_upgrade_smithing_template', 'coast_armor_trim_smithing_template',
|
||||
'sentry_armor_trim_smithing_template', 'bolt_armor_trim_smithing_template']
|
||||
BASES = ['diamond_sword', 'diamond_chestplate', 'diamond_pickaxe', 'iron_helmet', 'iron_chestplate', 'netherite_boots',
|
||||
'leather_leggings', 'golden_helmet', 'turtle_helmet', 'diamond_hoe']
|
||||
ADDITIONS = ['netherite_ingot', 'iron_ingot', 'gold_ingot', 'emerald', 'redstone', 'quartz', 'amethyst_shard',
|
||||
'lapis_lazuli', 'copper_ingot', 'diamond']
|
||||
|
||||
|
||||
def quote(text):
|
||||
@@ -97,6 +129,96 @@ class Gen:
|
||||
return snbt(rng.choice(pool), 1)
|
||||
return self.stack()
|
||||
|
||||
def cut_stack(self):
|
||||
"""Mostly something the stonecutter cuts, sometimes anything."""
|
||||
rng = self.rng
|
||||
if rng.random() < 0.75:
|
||||
return snbt('minecraft:' + rng.choice(CUTTABLE), rng.choice([1, 1, 2, 3, 10, 63, 64]))
|
||||
return self.stack()
|
||||
|
||||
def grind_stack(self):
|
||||
"""Mostly an enchanted or damaged tool or an enchanted book, sometimes anything."""
|
||||
rng = self.rng
|
||||
roll = rng.random()
|
||||
if roll > 0.8:
|
||||
return self.stack()
|
||||
levels = ','.join('"minecraft:%s":%d' % (e, rng.randrange(1, 4))
|
||||
for e in rng.sample(ENCHANTS, rng.choice([0, 1, 1, 2, 3])))
|
||||
comps = []
|
||||
if roll < 0.25:
|
||||
item = 'minecraft:' + rng.choice(['enchanted_book', 'enchanted_book', 'book'])
|
||||
if levels:
|
||||
comps.append('"minecraft:stored_enchantments":{%s}' % levels)
|
||||
count = 1 if rng.random() < 0.85 else 2
|
||||
else:
|
||||
item = 'minecraft:' + rng.choice(GRINDABLE)
|
||||
info = self.items.get(item, {})
|
||||
if levels:
|
||||
comps.append('"minecraft:enchantments":{%s}' % levels)
|
||||
if info.get('minecraft:max_damage') and rng.random() < 0.6:
|
||||
comps.append('"minecraft:damage":%d' % rng.randrange(0, info['minecraft:max_damage']))
|
||||
count = 1
|
||||
if rng.random() < 0.2:
|
||||
comps.append('"minecraft:repair_cost":%d' % rng.choice([1, 3, 7]))
|
||||
body = ',components:{%s}' % ','.join(comps) if comps else ''
|
||||
return '{id:%s,count:%d%s}' % (quote(item), count, body)
|
||||
|
||||
def anvil_stack(self):
|
||||
"""A tool to repair or enchant, an enchanted book, a repair material, a named item or anything."""
|
||||
rng = self.rng
|
||||
roll = rng.random()
|
||||
if roll < 0.45:
|
||||
stack = self.grind_stack()
|
||||
elif roll < 0.65:
|
||||
item = rng.choice(['iron_ingot', 'diamond', 'leather', 'oak_planks', 'phantom_membrane', 'string'])
|
||||
stack = snbt('minecraft:' + item, rng.choice([1, 1, 2, 3, 5, 64]))
|
||||
else:
|
||||
stack = self.stack()
|
||||
if rng.random() < 0.15:
|
||||
name = '"minecraft:custom_name":"%s"' % rng.choice(['Blade', 'Iron Sword', 'Old'])
|
||||
stack = stack.replace(',components:{', ',components:{%s,' % name) if ',components:{' in stack \
|
||||
else stack[:-1] + ',components:{%s}}' % name
|
||||
return stack
|
||||
|
||||
def smith_stack(self, slot=None):
|
||||
"""A template, a base or an addition (for `slot`, else any), sometimes anything."""
|
||||
rng = self.rng
|
||||
if rng.random() < 0.15:
|
||||
return self.stack()
|
||||
slot = rng.randrange(3) if slot is None else slot
|
||||
pool = [TEMPLATES, BASES, ADDITIONS][slot]
|
||||
item = 'minecraft:' + rng.choice(pool)
|
||||
count = 1 if slot == 1 else rng.choice([1, 1, 2, 5, 64])
|
||||
if slot == 1 and rng.random() < 0.3:
|
||||
return '{id:%s,count:1,components:{"minecraft:enchantments":{"minecraft:unbreaking":2}}}' % quote(item)
|
||||
return snbt(item, count)
|
||||
|
||||
def carto_stack(self):
|
||||
"""A filled map (some ids without data), paper, an empty map, a glass pane or anything."""
|
||||
rng = self.rng
|
||||
roll = rng.random()
|
||||
if roll < 0.4:
|
||||
return '{id:"minecraft:filled_map",count:%d,components:{"minecraft:map_id":%d}}' % (
|
||||
rng.choice([1, 1, 2, 3, 64]), rng.randrange(0, 7))
|
||||
if roll < 0.75:
|
||||
return snbt('minecraft:' + rng.choice(['paper', 'map', 'glass_pane']), rng.choice([1, 1, 2, 5, 64]))
|
||||
if roll < 0.78:
|
||||
# Something else with a map id: the map slot takes it.
|
||||
return '{id:"minecraft:paper",count:1,components:{"minecraft:map_id":%d}}' % rng.randrange(0, 7)
|
||||
return self.stack()
|
||||
|
||||
def book(self):
|
||||
"""A written or writable book with a few pages, or something else."""
|
||||
rng = self.rng
|
||||
pages = ','.join('"p%d"' % i for i in range(rng.choice([0, 1, 2, 3, 5])))
|
||||
roll = rng.random()
|
||||
if roll < 0.45:
|
||||
return ('{id:"minecraft:written_book",count:1,components:{"minecraft:written_book_content":'
|
||||
'{title:"T",author:"A",pages:[%s]}}}' % pages)
|
||||
if roll < 0.85:
|
||||
return '{id:"minecraft:writable_book",count:1,components:{"minecraft:writable_book_content":{pages:[%s]}}}' % pages
|
||||
return self.stack()
|
||||
|
||||
def recipe(self, slots, width, start=1):
|
||||
"""Fills the crafting grid (slots `start`..) with a small known recipe."""
|
||||
rng = self.rng
|
||||
@@ -123,6 +245,50 @@ class Gen:
|
||||
# The result: take it, shift it out, throw it.
|
||||
out.append([3, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'THROW', 'SWAP'])])
|
||||
continue
|
||||
if menu == 'stonecutter' and rng.random() < 0.25:
|
||||
# A recipe button (clickMenuButton), sometimes out of range or the selected one.
|
||||
out.append([rng.choice([0, 0, 1, 2, 3, 5, 10, 30, -1]), 0, 'BUTTON'])
|
||||
continue
|
||||
if menu == 'stonecutter' and rng.random() < 0.2:
|
||||
out.append([1, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])])
|
||||
continue
|
||||
if menu == 'anvil' and rng.random() < 0.15:
|
||||
out.append([0, 0, 'RENAME', rng.choice(NAMES)])
|
||||
continue
|
||||
if menu in ('anvil', 'smithing') and rng.random() < 0.2:
|
||||
result = 2 if menu == 'anvil' else 3
|
||||
out.append([result, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])])
|
||||
continue
|
||||
if menu == 'enchanting' and rng.random() < 0.25:
|
||||
# An offer button (clickMenuButton), sometimes out of range.
|
||||
out.append([rng.choice([0, 1, 2, 2, 3, -1]), 0, 'BUTTON'])
|
||||
continue
|
||||
if menu == 'beacon' and rng.random() < 0.3:
|
||||
# ServerboundSetBeaconPacket: powers, valid or not, or none.
|
||||
pick = lambda: 'minecraft:' + rng.choice(POWERS) if rng.random() < 0.8 else None
|
||||
primary, secondary = pick(), pick()
|
||||
if primary is None and secondary not in (None, 'minecraft:regeneration', 'minecraft:night_vision'):
|
||||
# validateEffects compares a null primary (Holder.equals: a NullPointerException).
|
||||
primary = secondary
|
||||
out.append([0, 0, 'SET_BEACON', primary, secondary])
|
||||
continue
|
||||
if menu == 'grindstone' and rng.random() < 0.2:
|
||||
out.append([2, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])])
|
||||
continue
|
||||
if menu == 'cartography' and rng.random() < 0.3:
|
||||
# The result: take it, shift it out, throw it, swap it, clone it.
|
||||
out.append([2, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP', 'CLONE'])])
|
||||
continue
|
||||
if menu == 'lectern':
|
||||
# The page buttons, a page jump, Take Book, and buttons it doesn't have; now and
|
||||
# then a click on the book's slot. Not SWAP or the drags: vanilla's bookAccess
|
||||
# hands out the block entity's own stack, which the swapped slot then shares.
|
||||
if rng.random() < 0.7:
|
||||
out.append([rng.choice([1, 1, 2, 2, 2, 3, 100, 101, 102, 104, 0, 4, 99, -1]), 0, 'BUTTON'])
|
||||
else:
|
||||
out.append([rng.choice([0, 0, -999]), rng.randrange(0, 2),
|
||||
rng.choice(['PICKUP', 'THROW', 'QUICK_MOVE', 'CLONE'])])
|
||||
continue
|
||||
if menu == 'crafter_be' and rng.random() < 0.2:
|
||||
out.append([rng.choice([0, 1, 4, 8, 8, 9, -1]), rng.randrange(0, 2), 'SLOT_STATE'])
|
||||
continue
|
||||
@@ -183,6 +349,58 @@ def main():
|
||||
slots[2] = g.loom_stack(0.6) if rng.random() < 0.4 else rng.choice(['-', '-', g.loom_stack()])
|
||||
# The result slot follows the inputs; a fixture stack there is rare.
|
||||
slots[3] = '-' if rng.random() < 0.9 else g.loom_stack()
|
||||
if menu == 'stonecutter':
|
||||
for i in rng.sample(range(2, size), 8):
|
||||
slots[i] = g.cut_stack()
|
||||
slots[0] = g.cut_stack() if rng.random() < 0.8 else '-'
|
||||
# The result follows the input and the selected recipe; a fixture stack there is rare.
|
||||
slots[1] = '-' if rng.random() < 0.9 else g.cut_stack()
|
||||
if menu == 'grindstone':
|
||||
for i in rng.sample(range(3, size), 10):
|
||||
slots[i] = g.grind_stack()
|
||||
slots[0] = g.grind_stack() if rng.random() < 0.7 else '-'
|
||||
slots[1] = g.grind_stack() if rng.random() < 0.6 else '-'
|
||||
# Two of the same tool, so mergeItems runs.
|
||||
if slots[0] != '-' and rng.random() < 0.3:
|
||||
slots[1] = slots[0] if rng.random() < 0.4 else g.grind_stack()
|
||||
# The result follows the inputs; a fixture stack there is rare.
|
||||
slots[2] = '-' if rng.random() < 0.9 else g.grind_stack()
|
||||
if menu == 'anvil':
|
||||
for i in rng.sample(range(3, size), 10):
|
||||
slots[i] = g.anvil_stack()
|
||||
slots[0] = g.anvil_stack() if rng.random() < 0.8 else '-'
|
||||
slots[1] = g.anvil_stack() if rng.random() < 0.6 else '-'
|
||||
if slots[0] != '-' and rng.random() < 0.25:
|
||||
slots[1] = slots[0]
|
||||
slots[2] = '-' if rng.random() < 0.9 else g.anvil_stack()
|
||||
if menu == 'smithing':
|
||||
for i in rng.sample(range(4, size), 12):
|
||||
slots[i] = g.smith_stack()
|
||||
for i in range(3):
|
||||
slots[i] = g.smith_stack(i) if rng.random() < 0.75 else '-'
|
||||
slots[3] = '-' if rng.random() < 0.9 else g.smith_stack()
|
||||
if menu == 'enchanting':
|
||||
lapis = lambda: snbt('minecraft:lapis_lazuli', rng.choice([1, 2, 3, 5, 64]))
|
||||
enchantable = lambda: snbt('minecraft:' + rng.choice(['iron_sword', 'book', 'diamond_pickaxe', 'bow',
|
||||
'golden_helmet', 'fishing_rod']), 1)
|
||||
for i in rng.sample(range(2, size), 10):
|
||||
slots[i] = rng.choice([lapis, enchantable, g.grind_stack])()
|
||||
slots[0] = rng.choice([enchantable, enchantable, g.grind_stack, g.stack])() if rng.random() < 0.8 else '-'
|
||||
slots[1] = lapis() if rng.random() < 0.7 else rng.choice(['-', g.stack()])
|
||||
if menu == 'beacon':
|
||||
pay = lambda: snbt('minecraft:' + rng.choice(PAYMENTS), rng.choice([1, 1, 1, 2, 64]))
|
||||
for i in rng.sample(range(1, size), 8):
|
||||
slots[i] = pay()
|
||||
slots[0] = pay() if rng.random() < 0.7 else rng.choice(['-', g.stack()])
|
||||
if menu == 'cartography':
|
||||
for i in rng.sample(range(3, size), 12):
|
||||
slots[i] = g.carto_stack()
|
||||
slots[0] = g.carto_stack() if rng.random() < 0.8 else '-'
|
||||
slots[1] = g.carto_stack() if rng.random() < 0.75 else '-'
|
||||
# The result follows the inputs; a fixture stack there is rare.
|
||||
slots[2] = '-' if rng.random() < 0.9 else g.carto_stack()
|
||||
if menu == 'lectern':
|
||||
slots[0] = g.book() if rng.random() < 0.85 else '-'
|
||||
if menu == 'crafter_be':
|
||||
slots[45] = '-'
|
||||
if rng.random() < 0.6:
|
||||
@@ -208,13 +426,36 @@ def main():
|
||||
return [rng.choice([0, 37, 1600]), 1600, rng.choice([0, 1, 57, 199]), rng.choice([200, 100])][i]
|
||||
if menu in ('crafter', 'crafter_be'):
|
||||
return rng.choice([0, 0, 1])
|
||||
if menu == 'loom':
|
||||
if menu in ('loom', 'stonecutter'):
|
||||
return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30])
|
||||
if menu == 'lectern':
|
||||
return rng.choice([-1, 0, 0, 1, 2, 4, 9])
|
||||
if menu == 'beacon':
|
||||
# the levels, then the powers (encodeEffect: id + 1)
|
||||
return rng.choice([0, 1, 2, 3, 4, 4]) if i == 0 else rng.choice([0, 0, 2, 4, 11])
|
||||
if menu == 'enchanting':
|
||||
# costs, the seed, then the clues
|
||||
return [rng.choice([0, 1, 2, 5, 15, 30]) for _ in range(3)][0] if i < 3 else \
|
||||
rng.randrange(-2**15, 2**15) if i == 3 else rng.choice([-1, -1, 0, 3, 12])
|
||||
return 0
|
||||
carried = (g.loom_stack() if menu == 'loom' else g.stack()) if rng.random() < 0.5 else '-'
|
||||
carried = {'loom': g.loom_stack, 'stonecutter': g.cut_stack, 'grindstone': g.grind_stack,
|
||||
'anvil': g.anvil_stack, 'smithing': g.smith_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-'
|
||||
if carried_food is not None:
|
||||
carried = carried_food
|
||||
cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots,
|
||||
if menu == 'lectern':
|
||||
carried = '-'
|
||||
extra = {}
|
||||
if menu == 'cartography':
|
||||
# Maps 0-4 exist (5 and 6 don't): [id, scale, locked].
|
||||
extra['maps'] = [[i, rng.choice([0, 0, 1, 3, 4]), rng.random() < 0.25] for i in range(5)]
|
||||
if rng.random() < 0.5:
|
||||
carried = g.carto_stack()
|
||||
if menu == 'lectern':
|
||||
# The inventory Take Book adds to (full, so the book drops, now and then).
|
||||
density = rng.choice([0.0, 0.3, 1.0])
|
||||
extra['inventory'] = [g.stack() if rng.random() < density else '-' for _ in range(36)]
|
||||
cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, **extra,
|
||||
'levels': rng.choice([0, 1, 3, 8, 30, 39, 40]),
|
||||
'carried': carried, 'data': [datum(i) for i in range(DATA.get(menu, 0))],
|
||||
'ops': g.ops(size, menu, slots)})
|
||||
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
|
||||
|
||||
Reference in New Issue
Block a user