Merge remote-tracking branch 'origin/main' into fix/st2-chat
This commit is contained in:
@@ -58,11 +58,12 @@ fn state(menu: &Menu) -> String {
|
||||
.map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref())))
|
||||
.collect();
|
||||
let line = format!(
|
||||
"{} | {} |{data} | {} | {}",
|
||||
"{} | {} |{data} | {} | {} | {}",
|
||||
slots.join(" "),
|
||||
canon_stack(menu.carried.as_ref()),
|
||||
menu.drops.join(";"),
|
||||
equipped.join(";")
|
||||
equipped.join(";"),
|
||||
menu.player_sounds.join(";")
|
||||
);
|
||||
if menu.kind() != Kind::Lectern {
|
||||
return line;
|
||||
@@ -171,6 +172,7 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
});
|
||||
menu.drops.clear();
|
||||
menu.equipped.clear();
|
||||
menu.player_sounds.clear();
|
||||
out += &format!("init {}\n", state(&menu));
|
||||
for op in case["ops"].as_array().ok_or("ops")? {
|
||||
let slot = op[0].as_i64().unwrap_or(0) as i32;
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
//! `BundleContents.Mutable`: what a bundle takes in and gives back, by
|
||||
//! weight. The menus (`menu`, `lan::menu`) run `BundleItem`'s click
|
||||
//! overrides on it.
|
||||
use crate::items::{ItemStack, Items};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// A bundle weight: vanilla's `Fraction`, exact and kept reduced.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Weight {
|
||||
n: i128,
|
||||
d: i128,
|
||||
}
|
||||
|
||||
fn gcd(a: i128, b: i128) -> i128 {
|
||||
let (mut a, mut b) = (a.abs(), b.abs());
|
||||
while b != 0 {
|
||||
(a, b) = (b, a % b);
|
||||
}
|
||||
a.max(1)
|
||||
}
|
||||
|
||||
impl Weight {
|
||||
const ZERO: Self = Self { n: 0, d: 1 };
|
||||
const ONE: Self = Self { n: 1, d: 1 };
|
||||
|
||||
fn new(n: i128, d: i128) -> Self {
|
||||
let g = gcd(n, d);
|
||||
Self { n: n / g, d: d / g }
|
||||
}
|
||||
|
||||
fn add(self, o: Self) -> Self {
|
||||
Self::new(self.n * o.d + o.n * self.d, self.d * o.d)
|
||||
}
|
||||
|
||||
fn sub(self, o: Self) -> Self {
|
||||
self.add(Self { n: -o.n, d: o.d })
|
||||
}
|
||||
|
||||
fn times(self, count: u32) -> Self {
|
||||
Self::new(self.n * i128::from(count), self.d)
|
||||
}
|
||||
|
||||
/// `this.divideBy(item).intValue()` (truncated), at least 0.
|
||||
fn how_many(self, item: Self) -> u32 {
|
||||
let q = (self.n * item.d) / (self.d * item.n);
|
||||
u32::try_from(q.max(0)).unwrap_or(u32::MAX)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sounds of `BundleItem` (`Entity.playSound` at the player): insert
|
||||
/// and remove one at volume 0.8 and pitch `0.8 + random * 0.4`, a failed
|
||||
/// insert at 1, 1.
|
||||
pub const INSERT: &str = "minecraft:item.bundle.insert";
|
||||
pub const INSERT_FAIL: &str = "minecraft:item.bundle.insert_fail";
|
||||
pub const REMOVE_ONE: &str = "minecraft:item.bundle.remove_one";
|
||||
|
||||
fn max_stack(items: &Items, stack: &ItemStack) -> u32 {
|
||||
items.get(&stack.item).map_or(64, |i| i.max_stack).max(1)
|
||||
}
|
||||
|
||||
/// The stack's `bundle_contents`, when it has the component.
|
||||
fn contents_of<'a>(items: &Items, stack: &'a ItemStack) -> Option<&'a [ItemStack]> {
|
||||
let inside = stack.data().map_or(&[][..], |d| &d.bundle_contents[..]);
|
||||
let bundle = items.get(&stack.item).is_some_and(|i| i.bundle);
|
||||
(bundle || !inside.is_empty()).then_some(inside)
|
||||
}
|
||||
|
||||
/// `BundleContents.getWeight`: a nested bundle weighs its contents plus
|
||||
/// 1/16, a beehive with bees 1, the rest 1 / max stack size.
|
||||
fn item_weight(items: &Items, stack: &ItemStack) -> Weight {
|
||||
if let Some(inside) = contents_of(items, stack) {
|
||||
return contents_weight(items, inside).add(Weight::new(1, 16));
|
||||
}
|
||||
let bees = stack
|
||||
.data()
|
||||
.and_then(|d| d.other("minecraft:bees"))
|
||||
.is_some_and(|b| matches!(b, Tag::List(l) if !l.is_empty()));
|
||||
if bees {
|
||||
Weight::ONE
|
||||
} else {
|
||||
Weight::new(1, i128::from(max_stack(items, stack)))
|
||||
}
|
||||
}
|
||||
|
||||
fn contents_weight(items: &Items, inside: &[ItemStack]) -> Weight {
|
||||
inside.iter().fold(Weight::ZERO, |w, s| {
|
||||
w.add(item_weight(items, s).times(s.count))
|
||||
})
|
||||
}
|
||||
|
||||
/// `BundleContents.canItemBeInBundle`: shulker boxes don't fit.
|
||||
pub fn can_be_in_bundle(stack: &ItemStack) -> bool {
|
||||
stack.count > 0 && !stack.item.ends_with("shulker_box")
|
||||
}
|
||||
|
||||
/// `BundleContents.Mutable`.
|
||||
pub struct Contents {
|
||||
items: Vec<ItemStack>,
|
||||
weight: Weight,
|
||||
}
|
||||
|
||||
impl Contents {
|
||||
/// The bundle's contents; None when the stack is no bundle.
|
||||
pub fn of(items: &Items, stack: &ItemStack) -> Option<Self> {
|
||||
let inside = contents_of(items, stack)?.to_vec();
|
||||
let weight = contents_weight(items, &inside);
|
||||
Some(Self {
|
||||
items: inside,
|
||||
weight,
|
||||
})
|
||||
}
|
||||
|
||||
/// `getMaxAmountToAdd` for `stack`'s kind of item.
|
||||
pub fn room_for(&self, items: &Items, stack: &ItemStack) -> u32 {
|
||||
Weight::ONE
|
||||
.sub(self.weight)
|
||||
.how_many(item_weight(items, stack))
|
||||
}
|
||||
|
||||
/// `tryInsert`: what fits moves to the front, merged with its kind.
|
||||
pub fn try_insert(&mut self, items: &Items, stack: &mut ItemStack) -> u32 {
|
||||
if !can_be_in_bundle(stack) {
|
||||
return 0;
|
||||
}
|
||||
let weight = item_weight(items, stack);
|
||||
let amount = stack
|
||||
.count
|
||||
.min(Weight::ONE.sub(self.weight).how_many(weight));
|
||||
if amount == 0 {
|
||||
return 0;
|
||||
}
|
||||
self.weight = self.weight.add(weight.times(amount));
|
||||
// ItemStack.isStackable: a damaged stack is damageable.
|
||||
let stackable = max_stack(items, stack) > 1 && stack.damage == 0;
|
||||
let same = self
|
||||
.items
|
||||
.iter()
|
||||
.position(|s| stackable && s.same_item_same_components(stack));
|
||||
let added = match same {
|
||||
Some(i) => {
|
||||
let mut merged = self.items.remove(i);
|
||||
merged.count += amount;
|
||||
stack.count -= amount;
|
||||
merged
|
||||
}
|
||||
None => {
|
||||
let mut part = stack.clone();
|
||||
part.count = amount;
|
||||
stack.count -= amount;
|
||||
part
|
||||
}
|
||||
};
|
||||
self.items.insert(0, added);
|
||||
amount
|
||||
}
|
||||
|
||||
/// `removeOne`: the first stack (Horizon keeps no selected item).
|
||||
pub fn remove_one(&mut self, items: &Items) -> Option<ItemStack> {
|
||||
if self.items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let stack = self.items.remove(0);
|
||||
self.weight = self
|
||||
.weight
|
||||
.sub(item_weight(items, &stack).times(stack.count));
|
||||
Some(stack)
|
||||
}
|
||||
|
||||
/// `toImmutable`, written back into the bundle's component.
|
||||
pub fn store(self, bundle: &mut ItemStack) {
|
||||
bundle.data_mut().bundle_contents = self.items;
|
||||
bundle.tidy();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Weight;
|
||||
|
||||
#[test]
|
||||
fn weights_add_up_exactly() {
|
||||
let w = Weight::new(1, 64)
|
||||
.times(32)
|
||||
.add(Weight::new(1, 16).times(4));
|
||||
assert_eq!(w, Weight::new(3, 4));
|
||||
assert_eq!(Weight::ONE.sub(w).how_many(Weight::new(1, 64)), 16);
|
||||
assert_eq!(Weight::ONE.sub(Weight::ONE).how_many(Weight::ONE), 0);
|
||||
// An over-full bundle (made by a command) has no room.
|
||||
let over = Weight::ONE.sub(Weight::new(5, 4));
|
||||
assert_eq!(over.how_many(Weight::new(1, 64)), 0);
|
||||
}
|
||||
}
|
||||
@@ -5499,6 +5499,20 @@ impl Game<'_> {
|
||||
Some(true)
|
||||
})
|
||||
}
|
||||
/// A sound a menu click made the player play (a bundle's insert or
|
||||
/// remove): `Entity.playSound` at the player.
|
||||
pub(super) fn player_menu_sound(&mut self, sound: &str) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
let (volume, pitch) = if sound == horizon_client::bundle::INSERT_FAIL {
|
||||
(1.0, 1.0)
|
||||
} else {
|
||||
(0.8, 0.8 + self.world.random.next_float() * 0.4)
|
||||
};
|
||||
self.audio.play(sound, Some(at), volume, pitch);
|
||||
}
|
||||
/// The open menu as the verified engine (`horizon_client::menu`): the
|
||||
/// game's slots are copied in, `run` acts on it, and the slots, carried
|
||||
/// stack, menu data and drops are copied back when it returns Some(true)
|
||||
@@ -5888,6 +5902,11 @@ impl Game<'_> {
|
||||
let carried = menu.carried.take();
|
||||
let dropped = std::mem::take(&mut menu.dropped);
|
||||
let sounds = std::mem::take(&mut menu.sounds);
|
||||
// A bundle's sounds are the player's own (`Entity.playSound`): the
|
||||
// client plays them as it clicks, predicting or not.
|
||||
for sound in std::mem::take(&mut menu.player_sounds) {
|
||||
self.player_menu_sound(sound);
|
||||
}
|
||||
let crafted = std::mem::take(&mut menu.crafted);
|
||||
let equipped = std::mem::take(&mut menu.equipped);
|
||||
for (i, stack) in after.into_iter().enumerate() {
|
||||
@@ -6132,6 +6151,17 @@ impl Game<'_> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// mouseClicked: an empty hand's PICKUP is the menu's click at once
|
||||
// (a right click on a bundle takes its first stack out).
|
||||
if let (Some(input), Some(_)) = (input, slot)
|
||||
&& self.remote.is_none()
|
||||
&& self.menu_click(slot, i32::from(right), input)
|
||||
{
|
||||
if let Some(key) = self.container {
|
||||
self.container_changed(key);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.click_inventory(right);
|
||||
}
|
||||
/// Mouse movement while a quick craft drag is running.
|
||||
|
||||
@@ -160,6 +160,9 @@ impl GuestPlay {
|
||||
|
||||
struct ItemRules<'a>(&'a horizon_client::items::Items);
|
||||
impl Rules for ItemRules<'_> {
|
||||
fn items(&self) -> &horizon_client::items::Items {
|
||||
self.0
|
||||
}
|
||||
fn max_stack(&self, item: &str) -> u32 {
|
||||
self.0.get(item).map_or(64, |i| i.max_stack)
|
||||
}
|
||||
|
||||
@@ -120,6 +120,8 @@ pub struct ItemInfo {
|
||||
pub dye: Option<String>,
|
||||
/// `block_transformer`: the registry entry an axe, hoe or shovel uses on blocks.
|
||||
pub block_transformer: Option<String>,
|
||||
/// Has a default `bundle_contents` (the bundles, `BundleItem`).
|
||||
pub bundle: bool,
|
||||
}
|
||||
/// `Item.Properties.craftRemainder` (not a data component, so not in the
|
||||
/// default-component report): what an item leaves in the grid when crafted with.
|
||||
@@ -593,6 +595,7 @@ impl Items {
|
||||
jukebox_song: c["minecraft:jukebox_playable"].as_str().map(str::to_owned),
|
||||
dye: c["minecraft:dye"].as_str().map(str::to_owned),
|
||||
block_transformer: c["minecraft:block_transformer"].as_str().map(str::to_owned),
|
||||
bundle: c.get("minecraft:bundle_contents").is_some(),
|
||||
crafting_remainder: CRAFT_REMAINDERS
|
||||
.iter()
|
||||
.find(|(item, _)| *item == name)
|
||||
|
||||
@@ -4,10 +4,15 @@
|
||||
//! clone, throw, quick craft (drag) and pickup all; items thrown out of a
|
||||
//! menu are returned for the game to drop.
|
||||
use super::guest::Guest;
|
||||
use crate::{items::ItemStack, world::World};
|
||||
use crate::{
|
||||
bundle::{Contents, can_be_in_bundle},
|
||||
items::{ItemStack, Items},
|
||||
world::World,
|
||||
};
|
||||
|
||||
/// What the menus need to know about items.
|
||||
pub trait Rules {
|
||||
fn items(&self) -> &Items;
|
||||
fn max_stack(&self, item: &str) -> u32;
|
||||
/// The armor slot (0 head .. 3 feet) an item can be worn in.
|
||||
fn armor_index(&self, item: &str) -> Option<usize>;
|
||||
@@ -364,6 +369,9 @@ fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) {
|
||||
return;
|
||||
}
|
||||
let right = button == 1;
|
||||
if bundle_click(view, i, right, rules) {
|
||||
return;
|
||||
}
|
||||
let (slot_item, carried) = (view.get(i), view.guest.carried.clone());
|
||||
match (slot_item, carried) {
|
||||
(None, None) => {}
|
||||
@@ -410,6 +418,84 @@ fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) {
|
||||
}
|
||||
}
|
||||
|
||||
/// `tryItemClickBehaviourOverride`: the carried stack's
|
||||
/// `BundleItem.overrideStackedOnOther`, then the clicked one's
|
||||
/// `overrideOtherStackedOnMe`. True when a bundle took the click.
|
||||
fn bundle_click(view: &mut View, i: usize, right: bool, rules: &dyn Rules) -> bool {
|
||||
let items = rules.items();
|
||||
let other = view.get(i);
|
||||
if let Some(mut carried) = view.guest.carried.clone()
|
||||
&& let Some(mut contents) = Contents::of(items, &carried)
|
||||
&& other.is_some() != right
|
||||
{
|
||||
match other {
|
||||
// tryTransfer: as much as fits, through `safeTake`.
|
||||
Some(mut other) => {
|
||||
if can_be_in_bundle(&other) {
|
||||
let amount = other.count.min(contents.room_for(items, &other));
|
||||
if amount > 0 {
|
||||
let mut taken = other.clone();
|
||||
taken.count = amount;
|
||||
other.count -= amount;
|
||||
view.set(i, (other.count > 0).then_some(other));
|
||||
contents.try_insert(items, &mut taken);
|
||||
}
|
||||
}
|
||||
}
|
||||
// removeOne into the empty slot (`safeInsert`); the rest goes back.
|
||||
None => {
|
||||
if let Some(mut stack) = contents.remove_one(items) {
|
||||
if view.may_place(i, &stack, rules) {
|
||||
let amount = stack.count.min(view.slot_max(i, &stack, rules));
|
||||
view.set(
|
||||
i,
|
||||
Some(ItemStack {
|
||||
count: amount,
|
||||
..stack.clone()
|
||||
}),
|
||||
);
|
||||
stack.count -= amount;
|
||||
}
|
||||
if stack.count > 0 {
|
||||
contents.try_insert(items, &mut stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
contents.store(&mut carried);
|
||||
view.guest.carried = Some(carried);
|
||||
return true;
|
||||
}
|
||||
let Some(mut bundle) = other else {
|
||||
return false;
|
||||
};
|
||||
let Some(mut contents) = Contents::of(items, &bundle) else {
|
||||
return false;
|
||||
};
|
||||
// Slot.allowModification: mayPickup and mayPlace of its item.
|
||||
let allowed = view.may_place(i, &bundle, rules);
|
||||
match (view.guest.carried.take(), right) {
|
||||
(Some(mut carried), false) => {
|
||||
if allowed {
|
||||
contents.try_insert(items, &mut carried);
|
||||
}
|
||||
view.guest.carried = (carried.count > 0).then_some(carried);
|
||||
}
|
||||
(None, true) => {
|
||||
if allowed {
|
||||
view.guest.carried = contents.remove_one(items);
|
||||
}
|
||||
}
|
||||
(carried, _) => {
|
||||
view.guest.carried = carried;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
contents.store(&mut bundle);
|
||||
view.set(i, Some(bundle));
|
||||
true
|
||||
}
|
||||
|
||||
fn swap(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) {
|
||||
let Ok(i) = usize::try_from(slot) else {
|
||||
return;
|
||||
@@ -538,3 +624,116 @@ fn quick_craft(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::lan::{Joined, PlayerSender};
|
||||
use horizon_protocol::packets::configuration::ClientInformation;
|
||||
use std::sync::{Arc, atomic::AtomicI32, mpsc};
|
||||
|
||||
struct ItemRules(Items);
|
||||
impl Rules for ItemRules {
|
||||
fn items(&self) -> &Items {
|
||||
&self.0
|
||||
}
|
||||
fn max_stack(&self, item: &str) -> u32 {
|
||||
self.0.get(item).map_or(64, |i| i.max_stack)
|
||||
}
|
||||
fn armor_index(&self, _: &str) -> Option<usize> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn guest() -> Guest {
|
||||
let (tx, _rx) = mpsc::channel();
|
||||
Guest::new(
|
||||
Joined {
|
||||
conn: 2,
|
||||
uuid: 2,
|
||||
name: "Alex".into(),
|
||||
properties: Vec::new(),
|
||||
info: ClientInformation::new(8),
|
||||
brand: "test".into(),
|
||||
sender: PlayerSender::new(tx, Arc::default()),
|
||||
latency: Arc::new(AtomicI32::new(0)),
|
||||
address: "127.0.0.1:25565".parse().unwrap(),
|
||||
},
|
||||
2,
|
||||
[0.0, 64.0, 0.0],
|
||||
8,
|
||||
)
|
||||
}
|
||||
|
||||
fn contents(stack: &Option<ItemStack>) -> Vec<(String, u32)> {
|
||||
let inside = stack.as_ref().and_then(|s| s.data());
|
||||
inside.map_or(Vec::new(), |d| {
|
||||
d.bundle_contents
|
||||
.iter()
|
||||
.map(|s| (s.item.to_string(), s.count))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// A guest's chest clicks run `BundleItem`'s overrides: a carried
|
||||
/// bundle takes a slot's stack and drops its first one into an empty
|
||||
/// slot; a stack clicked onto a bundle goes in, as far as it fits.
|
||||
#[test]
|
||||
fn guest_chest_clicks_fill_and_empty_bundles() {
|
||||
let root = std::env::var_os("HORIZON_RESOURCES")
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION)
|
||||
});
|
||||
if !root.join("items.json").exists() {
|
||||
eprintln!("skipping resource-backed bundle check: {}", root.display());
|
||||
return;
|
||||
}
|
||||
let registry = horizon_world::level::data::load_registry(&root).unwrap();
|
||||
let facts = crate::blocks::BlockFacts::load(&root, ®istry).unwrap();
|
||||
let rules = ItemRules(Items::load(&root, ®istry, &facts).unwrap());
|
||||
let mut g = guest();
|
||||
let mut chest = vec![
|
||||
Some(ItemStack::new("minecraft:stone", 48)),
|
||||
None,
|
||||
Some(ItemStack::new("minecraft:bundle", 1)),
|
||||
];
|
||||
let mut drag = None;
|
||||
let mut view = View {
|
||||
guest: &mut g,
|
||||
container: Some(&mut chest),
|
||||
};
|
||||
view.guest.carried = Some(ItemStack::new("minecraft:bundle", 1));
|
||||
// Left click with the bundle: the stone goes in.
|
||||
click(&mut view, &mut drag, 0, 0, input::PICKUP, &rules);
|
||||
assert_eq!(view.get(0), None);
|
||||
assert_eq!(
|
||||
contents(&view.guest.carried),
|
||||
[("minecraft:stone".into(), 48)]
|
||||
);
|
||||
// Right click on an empty slot: the stone comes back out.
|
||||
click(&mut view, &mut drag, 1, 1, input::PICKUP, &rules);
|
||||
assert_eq!(view.get(1).map(|s| s.count), Some(48));
|
||||
assert_eq!(contents(&view.guest.carried), []);
|
||||
// Ender pearls (1/16 each) onto the bundle in the chest: 16 fit.
|
||||
view.guest.carried = Some(ItemStack::new("minecraft:ender_pearl", 16));
|
||||
click(&mut view, &mut drag, 2, 0, input::PICKUP, &rules);
|
||||
assert_eq!(view.guest.carried, None);
|
||||
let bundle = view.get(2);
|
||||
assert_eq!(contents(&bundle), [("minecraft:ender_pearl".into(), 16)]);
|
||||
// Full: more stone stays in hand.
|
||||
view.guest.carried = Some(ItemStack::new("minecraft:stone", 5));
|
||||
click(&mut view, &mut drag, 2, 0, input::PICKUP, &rules);
|
||||
assert_eq!(view.guest.carried.as_ref().map(|s| s.count), Some(5));
|
||||
// Right click on it with an empty hand takes the pearls out.
|
||||
view.guest.carried = None;
|
||||
click(&mut view, &mut drag, 2, 1, input::PICKUP, &rules);
|
||||
assert_eq!(
|
||||
view.guest.carried.as_ref().map(|s| (&*s.item, s.count)),
|
||||
Some(("minecraft:ender_pearl", 16))
|
||||
);
|
||||
assert_eq!(contents(&view.get(2)), []);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ pub mod border_render;
|
||||
pub mod bossbar;
|
||||
pub mod breaking;
|
||||
pub mod brewing;
|
||||
pub mod bundle;
|
||||
pub mod camera;
|
||||
pub mod cauldron;
|
||||
pub mod chat;
|
||||
|
||||
@@ -16,6 +16,7 @@ use crate::{
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
mod bundle;
|
||||
pub mod place;
|
||||
|
||||
/// What a menu needs to know about items and recipes.
|
||||
@@ -276,6 +277,9 @@ pub struct Menu {
|
||||
pub loom_patterns: Vec<Arc<str>>,
|
||||
/// Sounds the menu plays (`ui.loom.take_result`), for the caller.
|
||||
pub sounds: Vec<&'static str>,
|
||||
/// Sounds the player makes (a bundle's insert and remove), for the
|
||||
/// caller to play at the player as `Entity.playSound`.
|
||||
pub player_sounds: Vec<&'static str>,
|
||||
/// Recipes whose result was taken (`awardUsedRecipes`), for the caller.
|
||||
pub crafted: Vec<String>,
|
||||
/// `LivingEntity.onEquipItem` calls that change the item: the
|
||||
@@ -671,6 +675,7 @@ impl Menu {
|
||||
quick_slots: Vec::new(),
|
||||
loom_patterns: Vec::new(),
|
||||
sounds: Vec::new(),
|
||||
player_sounds: Vec::new(),
|
||||
crafted: Vec::new(),
|
||||
equipped: Vec::new(),
|
||||
merchant: None,
|
||||
@@ -931,6 +936,23 @@ impl Menu {
|
||||
}
|
||||
}
|
||||
|
||||
/// `slotsChanged(player.getInventory())`, which a bundle click calls
|
||||
/// (`BundleItem.broadcastChangesOnContainerMenu`): the menus that don't
|
||||
/// check which container changed recompute from their inputs.
|
||||
fn inventory_slots_changed(&mut self, env: &Env) {
|
||||
match self.kind {
|
||||
Kind::Inventory | Kind::Crafting => self.recompute(env),
|
||||
Kind::Loom => self.loom_changed(env),
|
||||
Kind::Stonecutter => self.stone_changed(env),
|
||||
Kind::Cartography => self.carto_changed(env),
|
||||
Kind::Merchant => self.merchant_update(env),
|
||||
// ItemCombinerMenu.slotsChanged only for its inputs; the
|
||||
// smithing table's hasRecipeError always.
|
||||
Kind::Smithing => self.smith_error(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `EnchantmentMenu.clickMenuButton`'s checks: the lapis, the cost and
|
||||
/// the levels (creative pays nothing). The enchanting itself needs a
|
||||
/// level and is the caller's (`enchant_button`).
|
||||
@@ -2536,10 +2558,12 @@ impl Menu {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The PICKUP branch of `doClick` (without the bundle overrides), ending
|
||||
/// with `slot.setChanged()`.
|
||||
/// The PICKUP branch of `doClick`: a bundle's override, else the
|
||||
/// plain click, ending with `slot.setChanged()`.
|
||||
fn pickup(&mut self, env: &Env, s: usize, primary: bool) {
|
||||
self.pickup_inner(env, s, primary);
|
||||
if !self.bundle_click(env, s, primary) {
|
||||
self.pickup_inner(env, s, primary);
|
||||
}
|
||||
self.slot_changed(env, s);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! `BundleItem`'s click overrides in a PICKUP click
|
||||
//! (`tryItemClickBehaviourOverride`).
|
||||
use super::{Env, Menu, tidy};
|
||||
use crate::bundle::{Contents, INSERT, INSERT_FAIL, REMOVE_ONE, can_be_in_bundle};
|
||||
|
||||
impl Menu {
|
||||
/// The carried stack's `overrideStackedOnOther`, then the clicked
|
||||
/// one's `overrideOtherStackedOnMe`. True when a bundle took the click.
|
||||
pub(super) fn bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool {
|
||||
let took = self.carried_bundle_click(env, s, primary)
|
||||
|| self.clicked_bundle_click(env, s, primary);
|
||||
if took {
|
||||
// broadcastChangesOnContainerMenu: the open menu's
|
||||
// slotsChanged for the player's inventory.
|
||||
self.inventory_slots_changed(env);
|
||||
}
|
||||
took
|
||||
}
|
||||
|
||||
/// `BundleItem.overrideStackedOnOther`: the carried bundle on a slot.
|
||||
fn carried_bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool {
|
||||
let Some(mut contents) = self
|
||||
.carried
|
||||
.as_ref()
|
||||
.and_then(|c| Contents::of(env.items, c))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
match (self.slot(s).cloned(), primary) {
|
||||
(Some(other), true) => {
|
||||
// tryTransfer: what fits, taken by the slot's rules.
|
||||
let mut moved = 0;
|
||||
if can_be_in_bundle(&other) {
|
||||
let room = contents.room_for(env.items, &other);
|
||||
if let Some(mut taken) = self.safe_take(env, s, other.count, room) {
|
||||
moved = contents.try_insert(env.items, &mut taken);
|
||||
}
|
||||
}
|
||||
self.player_sounds
|
||||
.push(if moved > 0 { INSERT } else { INSERT_FAIL });
|
||||
}
|
||||
(None, false) => {
|
||||
if let Some(stack) = contents.remove_one(env.items) {
|
||||
let count = stack.count;
|
||||
let mut remainder = Some(stack);
|
||||
self.safe_insert(env, s, &mut remainder, count);
|
||||
match remainder {
|
||||
Some(mut rest) => {
|
||||
contents.try_insert(env.items, &mut rest);
|
||||
}
|
||||
None => self.player_sounds.push(REMOVE_ONE),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
if let Some(carried) = self.carried.as_mut() {
|
||||
contents.store(carried);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// `BundleItem.overrideOtherStackedOnMe`: a click on a bundle in a slot.
|
||||
fn clicked_bundle_click(&mut self, env: &Env, s: usize, primary: bool) -> bool {
|
||||
let Some(mut bundle) = self.slot(s).cloned() else {
|
||||
return false;
|
||||
};
|
||||
let Some(mut contents) = Contents::of(env.items, &bundle) else {
|
||||
return false;
|
||||
};
|
||||
let allowed = self.allow_modification(env, s);
|
||||
match (self.carried.take(), primary) {
|
||||
(Some(mut other), true) => {
|
||||
let moved = if allowed {
|
||||
contents.try_insert(env.items, &mut other)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
self.player_sounds
|
||||
.push(if moved > 0 { INSERT } else { INSERT_FAIL });
|
||||
self.carried = Some(other);
|
||||
tidy(&mut self.carried);
|
||||
}
|
||||
(None, false) => {
|
||||
if allowed && let Some(removed) = contents.remove_one(env.items) {
|
||||
self.player_sounds.push(REMOVE_ONE);
|
||||
self.carried = Some(removed);
|
||||
}
|
||||
}
|
||||
(carried, _) => {
|
||||
// toggleSelectedItem(-1): Horizon keeps no selected item.
|
||||
self.carried = carried;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// `self.set(BUNDLE_CONTENTS, ...)` changes the slot's stack in place.
|
||||
contents.store(&mut bundle);
|
||||
let slot = self.slots[s];
|
||||
self.containers[slot.container][slot.index] = Some(bundle);
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,9 @@ public final class VanillaMenuOracle {
|
||||
static final List<String> drops = new ArrayList<>();
|
||||
/** onEquipItem calls that change the item (its sound and game event): slot and new stack. */
|
||||
static final List<String> equips = new ArrayList<>();
|
||||
/** The sounds the player played ({@code Entity.playSound}: a bundle's insert and remove). */
|
||||
static final List<String> sounds = new ArrayList<>();
|
||||
static final net.minecraft.util.RandomSource soundRandom = net.minecraft.util.RandomSource.create(0L);
|
||||
/** 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. */
|
||||
@@ -99,6 +102,8 @@ public final class VanillaMenuOracle {
|
||||
@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) { }
|
||||
// A bundle sound's pitch: 0.8 + level.getRandom().nextFloat() * 0.4.
|
||||
@Override public net.minecraft.util.RandomSource getRandom() { return soundRandom; }
|
||||
}
|
||||
|
||||
/** The maps of the case's level, by id, and the next free id. */
|
||||
@@ -127,6 +132,9 @@ public final class VanillaMenuOracle {
|
||||
if (!ItemStack.isSameItemSameComponents(old, now)) equips.add(slot.getName() + ":" + ParityData.canon(now));
|
||||
}
|
||||
@Override public boolean hasDisconnected() { return false; }
|
||||
@Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) {
|
||||
sounds.add(sound.location().toString());
|
||||
}
|
||||
@Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) {
|
||||
if (!stack.isEmpty()) drops.add(ParityData.canon(stack));
|
||||
return null;
|
||||
@@ -251,9 +259,9 @@ public final class VanillaMenuOracle {
|
||||
// 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) + " | " + String.join(";", sounds) + " | inv" + items;
|
||||
}
|
||||
return state(menu, inv) + " | " + String.join(";", equips);
|
||||
return state(menu, inv) + " | " + String.join(";", equips) + " | " + String.join(";", sounds);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
@@ -271,6 +279,7 @@ public final class VanillaMenuOracle {
|
||||
try {
|
||||
drops.clear();
|
||||
equips.clear();
|
||||
sounds.clear();
|
||||
var world = make(World.class);
|
||||
world.server = make(Server.class);
|
||||
var player = make(FakePlayer.class);
|
||||
@@ -325,6 +334,7 @@ public final class VanillaMenuOracle {
|
||||
for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt());
|
||||
drops.clear();
|
||||
equips.clear();
|
||||
sounds.clear();
|
||||
out.println("init " + clickState(menu, inv));
|
||||
for (var opJson : f.getAsJsonArray("ops")) {
|
||||
var op = opJson.getAsJsonArray();
|
||||
|
||||
+6
-1
@@ -3772,13 +3772,18 @@ def check_hands(host, guest, out):
|
||||
player.raw('select', 'minecraft:bow')
|
||||
aim_cow()
|
||||
assert player('looking_at')['kind'] == 'entity', f'the {label} does not aim at the cow'
|
||||
# Half drawn: a full draw is a crit, up to 10 damage (AbstractArrow.onHitEntity), which
|
||||
# kills the 10 health cow one shot in five. Under 20 ticks the arrow does at most 6.
|
||||
player.raw('mouse', 'right', 'down')
|
||||
player.wait(25)
|
||||
player.wait(10)
|
||||
drawn = player('state')['using']
|
||||
player.raw('mouse', 'right', 'up')
|
||||
player.wait(20)
|
||||
assert drawn, f'the {label}\'s bow is not drawn at the cow'
|
||||
assert counts().get('minecraft:arrow') == 5, f'the {label} shot no arrow: {counts()}'
|
||||
aim_cow()
|
||||
cow = player('looking_at').get('entity') or {}
|
||||
assert cow.get('health', 0) > 0, f'the {label}\'s arrow killed the cow: {cow}'
|
||||
player('command', command='clear @s')
|
||||
player('command', command='give @s minecraft:golden_apple')
|
||||
player.wait(5)
|
||||
|
||||
@@ -22,8 +22,10 @@ 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.
|
||||
cooking, other clicks keep its progress). Bundles (empty, partly and fully
|
||||
loaded, nested) are among the stacks and often in hand, for BundleItem's click
|
||||
overrides. After every click the slots, carried stack, data slots, drops and
|
||||
the player's sounds are compared.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
@@ -37,6 +39,8 @@ 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, '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}
|
||||
# Where a carried bundle is common: the containers that hold anything.
|
||||
BUNDLE_MENUS = {'inventory', 'chest1', 'chest3', 'shulker', 'hopper', 'dispenser'}
|
||||
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}
|
||||
@@ -91,8 +95,10 @@ def snbt(item, count, damage=0, curse=False, potion=None):
|
||||
|
||||
|
||||
class Gen:
|
||||
def __init__(self, rng, items):
|
||||
def __init__(self, rng, items, bundles=None):
|
||||
self.rng = rng
|
||||
# Bundles come from their own generator, so the other stacks stay as they were.
|
||||
self.bundles = bundles or random.Random(0)
|
||||
self.items = items
|
||||
self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items]
|
||||
self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k
|
||||
@@ -108,7 +114,37 @@ class Gen:
|
||||
damage = rng.randrange(1, info['minecraft:max_damage'])
|
||||
count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)])
|
||||
potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None
|
||||
return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion)
|
||||
stack = snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion)
|
||||
return self.bundle() if self.bundles.random() < 0.06 else stack
|
||||
|
||||
def bundle(self, room=64):
|
||||
"""A bundle, empty or holding up to its weight (in 64ths: 1 per item of a
|
||||
64-stack, 4 of a 16-stack, 64 of a tool), now and then another bundle."""
|
||||
return self.loaded_bundle(room)[0]
|
||||
|
||||
def loaded_bundle(self, room):
|
||||
rng = self.bundles
|
||||
color = rng.choice(['', '', 'red_', 'light_blue_'])
|
||||
inside, used = [], 0
|
||||
for _ in range(rng.choice([0, 0, 1, 1, 2, 3, 5])):
|
||||
if room == 64 and rng.random() < 0.1:
|
||||
# A nested bundle weighs its contents plus 1/16.
|
||||
if room - used > 4:
|
||||
nested, weight = self.loaded_bundle(min(room - used - 4, 16))
|
||||
inside.append(nested)
|
||||
used += weight + 4
|
||||
continue
|
||||
item = rng.choice(self.pool)
|
||||
top = self.items[item].get('minecraft:max_stack_size', 64)
|
||||
unit = 64 // top
|
||||
if unit > room - used or 'shulker_box' in item:
|
||||
continue
|
||||
most = min(top, (room - used) // unit)
|
||||
count = min(most, rng.choice([1, 1, 2, rng.randrange(1, most + 1)]))
|
||||
used += count * unit
|
||||
inside.append(snbt(item, count))
|
||||
body = ',components:{"minecraft:bundle_contents":[%s]}' % ','.join(inside) if inside else ''
|
||||
return '{id:"minecraft:%sbundle",count:1%s}' % (color, body), used
|
||||
|
||||
def slots(self, size, density):
|
||||
return [self.stack() if self.rng.random() < density else '-' for _ in range(size)]
|
||||
@@ -333,7 +369,7 @@ def main():
|
||||
vanilla.compile('ParityData', 'VanillaMenuOracle')
|
||||
items = json.loads((lib.RESOURCES / 'items.json').read_text())
|
||||
rng = random.Random(args.seed)
|
||||
g = Gen(rng, items)
|
||||
g = Gen(rng, items, random.Random(args.seed + 1))
|
||||
cases = []
|
||||
chosen = args.menus.split(',') if args.menus else list(MENUS)
|
||||
for n in range(args.cases):
|
||||
@@ -442,6 +478,9 @@ def main():
|
||||
'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
|
||||
elif menu in BUNDLE_MENUS and g.bundles.random() < 0.3:
|
||||
# A bundle in hand, emptied into slots and filled from them.
|
||||
carried = g.bundle()
|
||||
if menu == 'lectern':
|
||||
carried = '-'
|
||||
extra = {}
|
||||
|
||||
Reference in New Issue
Block a user