Merge pull request #2687 from kacpherek/feat/shelf-use

🤖 Agent: Proven in union R1 (branch union/cg19-r1, main + 83 of kacpherek's PRs): the 98 harnesses it can affect, clippy -D warnings, tests, lan_e2e in-frame and on the server thread.
This commit is contained in:
Ludovic Marie
2026-10-27 14:19:23 +01:00
committed by GitHub
8 changed files with 350 additions and 5 deletions
+23
View File
@@ -103,6 +103,22 @@ pub enum BlockEntity {
/// `DaylightDetectorBlockEntity`: no data, only the ticker
/// (`DaylightDetectorBlock.tickEntity`).
DaylightDetector,
/// `ChiseledBookShelfBlockEntity`: a `Container` of six one-book slots.
ChiseledBookshelf(Box<ChiseledBookshelf>),
}
/// `ChiseledBookShelfBlockEntity`: six slots and `lastInteractedSlot`.
#[derive(Clone, Debug, PartialEq)]
pub struct ChiseledBookshelf {
pub items: [Option<ItemStack>; 6],
pub last_slot: i32,
}
impl Default for ChiseledBookshelf {
fn default() -> Self {
Self {
items: Default::default(),
last_slot: -1,
}
}
}
/// `TheEndGatewayBlockEntity`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -407,6 +423,9 @@ impl BlockEntity {
if name == "minecraft:campfire" || name == "minecraft:soul_campfire" {
return Some(Self::Campfire(Box::default()));
}
if name == "minecraft:chiseled_bookshelf" {
return Some(Self::ChiseledBookshelf(Box::default()));
}
let size = match name {
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
n if n.ends_with("copper_chest") => 27,
@@ -447,6 +466,7 @@ impl BlockEntity {
Self::EndGateway(_) => "minecraft:end_gateway",
Self::DaylightDetector => "minecraft:daylight_detector",
Self::Campfire(_) => "minecraft:campfire",
Self::ChiseledBookshelf(_) => "minecraft:chiseled_bookshelf",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -471,6 +491,7 @@ impl BlockEntity {
Self::Banner(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
Self::Campfire(c) => c.items.iter().flatten().cloned().collect(),
Self::ChiseledBookshelf(b) => b.items.iter().flatten().cloned().collect(),
}
}
pub fn slots(&self) -> &[Option<ItemStack>] {
@@ -488,6 +509,7 @@ impl BlockEntity {
| Self::Skull(_)
| Self::DaylightDetector => &[],
Self::Crafter(c) => &c.items,
Self::ChiseledBookshelf(b) => &b.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
@@ -513,6 +535,7 @@ impl BlockEntity {
| Self::Skull(_)
| Self::DaylightDetector => &mut [],
Self::Crafter(c) => &mut c.items,
Self::ChiseledBookshelf(b) => &mut b.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
+17 -3
View File
@@ -24,6 +24,7 @@ mod campfire_douse;
mod cartography;
mod cat_spawner;
mod chat;
mod chiseled_bookshelf;
mod client_ambient;
mod clipboard;
mod combat;
@@ -742,7 +743,7 @@ impl LevelAccess for GameLevel<'_> {
&self,
pos: BlockPos,
state: BlockStateId,
_direction: Direction,
direction: Direction,
) -> i32 {
if let Some(s) = self.registry.state(state)
&& s.name == "minecraft:detector_rail"
@@ -775,6 +776,11 @@ impl LevelAccess for GameLevel<'_> {
if let Some(signal) = books::lectern_signal(self.world, pos) {
return signal;
}
if let Some(signal) =
machines::shelf_signal(self.world, self.registry, state, pos, direction)
{
return signal;
}
machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos)
}
fn block_entity_signal(
@@ -3994,6 +4000,12 @@ impl Game<'_> {
self.swing_arm();
return Ok(true);
}
if let Some(swings) = self.use_chiseled_bookshelf(hit, held.as_ref()) {
if swings {
self.swing_arm();
}
return Ok(true);
}
if self.use_composter(hit.pos, held.as_ref()) {
self.swing_arm();
return Ok(true);
@@ -5877,7 +5889,8 @@ impl Game<'_> {
| BlockEntity::EndGateway(_)
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector
| BlockEntity::Campfire(_),
| BlockEntity::Campfire(_)
| BlockEntity::ChiseledBookshelf(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -6150,7 +6163,8 @@ impl Game<'_> {
| BlockEntity::EndGateway(_)
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector
| BlockEntity::Campfire(_),
| BlockEntity::Campfire(_)
| BlockEntity::ChiseledBookshelf(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -0,0 +1,178 @@
//! Chiseled bookshelves: `ChiseledBookShelfBlock.useItemOn` / `useWithoutItem`
//! (a book into the slot under the crosshair, or out of it) and
//! `ChiseledBookShelfBlockEntity.updateState`, which also follows the books a
//! hopper or dropper moved (`machines::container_changed`). The slots' books
//! show through the block state's `slot_N_occupied`, which reaches a server's
//! clients with the block update.
use super::{Game, Hit, machines::dir_from_name};
use horizon_client::{containers::BlockEntity, items::ItemStack, mobs::Who};
use horizon_core::{
geometry::{Direction, Vec3},
position::BlockPos,
};
use horizon_world::level::{flags, hit_slot};
const BLOCK: &str = "minecraft:chiseled_bookshelf";
impl Game<'_> {
/// `useItemOn` with `held` in the acting hand, then `useWithoutItem` on
/// the main hand's turn: None when the block passes the click, else
/// whether the use succeeded and the arm swings (a click on an empty slot
/// without a book only consumes it).
pub(super) fn use_chiseled_bookshelf(
&mut self,
hit: &Hit,
held: Option<&ItemStack>,
) -> Option<bool> {
let pos = hit.pos;
let state = self.world.block(pos[0], pos[1], pos[2]);
let info = self
.pack
.assets
.registry
.state(state)
.filter(|s| s.name == BLOCK)?;
let facing = info
.properties
.get("facing")
.and_then(|f| dir_from_name(f))?;
let face = Direction::ALL
.into_iter()
.find(|d| d.normal() == hit.face)?;
let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]);
let slot = hit_slot(
facing,
face,
BlockPos::new(pos[0], pos[1], pos[2]),
at,
2,
3,
)?;
let occupied = info
.properties
.get(&format!("slot_{slot}_occupied"))
.map(String::as_str)
== Some("true");
let book = held.filter(|s| {
self.res
.items()
.item_tags
.get("minecraft:bookshelf_books")
.is_some_and(|m| m.contains(&*s.item))
});
let centre = pos.map(|v| f64::from(v) + 0.5);
if let Some(book) = book
&& !occupied
{
// addBook: one book goes in (a creative player keeps theirs).
let book = book.clone();
self.stats.add("used", &book.item, 1);
let sound = if &*book.item == "minecraft:enchanted_book" {
"minecraft:block.chiseled_bookshelf.insert.enchanted"
} else {
"minecraft:block.chiseled_bookshelf.insert"
};
self.bookshelf_items(pos)?[slot] = Some(ItemStack {
count: 1,
..book.clone()
});
self.consume_held();
self.chiseled_bookshelf_update_state(pos, slot);
self.audio.play(sound, Some(centre), 1.0, 1.0);
self.trigger_block("minecraft:item_used_on_block", pos, &book);
return Some(true);
}
// TRY_WITH_EMPTY_HAND: only the main hand goes on to useWithoutItem.
if self.hand != horizon_client::first_person::Hand::Main {
return None;
}
if !occupied {
return Some(false);
}
// removeBook: the book goes to the inventory, or is dropped.
let retrieved = self.bookshelf_items(pos)?[slot].take()?;
self.chiseled_bookshelf_update_state(pos, slot);
let sound = if &*retrieved.item == "minecraft:enchanted_book" {
"minecraft:block.chiseled_bookshelf.pickup.enchanted"
} else {
"minecraft:block.chiseled_bookshelf.pickup"
};
self.audio.play(sound, Some(centre), 1.0, 1.0);
self.give_or_drop(retrieved);
self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None);
Some(true)
}
/// The bookshelf's six slots (made if the block has no block entity yet).
fn bookshelf_items(&mut self, pos: [i32; 3]) -> Option<&mut [Option<ItemStack>; 6]> {
let entity = self
.world
.block_entities
.get_or_insert_with((pos[0], pos[1], pos[2]), || {
BlockEntity::ChiseledBookshelf(Box::default())
});
match entity {
BlockEntity::ChiseledBookshelf(b) => Some(&mut b.items),
_ => None,
}
}
/// `ChiseledBookShelfBlockEntity.updateState`: `slot` becomes the last
/// one touched, the block state takes the slots' occupancy
/// (`setBlockAndUpdate`) and `BLOCK_CHANGE` goes out.
fn chiseled_bookshelf_update_state(&mut self, pos: [i32; 3], slot: usize) {
let key = (pos[0], pos[1], pos[2]);
let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get_mut(&key)
else {
return;
};
b.last_slot = slot as i32;
let occupied: Vec<bool> = b.items.iter().map(Option::is_some).collect();
let registry = self.pack.assets.registry;
let Some(mut state) = registry
.state(self.world.block(pos[0], pos[1], pos[2]))
.cloned()
else {
return;
};
for (i, occupied) in occupied.into_iter().enumerate() {
state
.properties
.insert(format!("slot_{i}_occupied"), occupied.to_string());
}
let Some(new) = registry.id(&state) else {
return;
};
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| b.set_block(level, ticks, at, new, flags::UPDATE_ALL));
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
self.post_block_game_event("minecraft:block_change", pos, None, Some(new));
}
/// The books a hopper or dropper put in or took out: the slot whose
/// occupancy no longer matches the block state is the one `setItem` or
/// `removeItem` updated.
pub(super) fn chiseled_bookshelf_synced(&mut self, pos: (i32, i32, i32)) {
let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get(&pos) else {
return;
};
let Some(info) = self
.pack
.assets
.registry
.state(self.world.block(pos.0, pos.1, pos.2))
else {
return;
};
let moved = (0..6).rev().find(|i| {
let shown = info
.properties
.get(&format!("slot_{i}_occupied"))
.map(String::as_str);
b.items[*i].is_some() != (shown == Some("true"))
});
if let Some(slot) = moved {
self.chiseled_bookshelf_update_state([pos.0, pos.1, pos.2], slot);
}
}
}
+54 -1
View File
@@ -41,6 +41,8 @@ enum Kind {
Crafter,
/// `BrewingStandBlockEntity` (a `WorldlyContainer`).
Brewing,
/// `ChiseledBookShelfBlockEntity`: books only, one to a slot.
Bookshelf,
/// `ComposterBlock.getContainer` at this level (a `WorldlyContainerHolder`
/// without a block entity): input below 7, empty at 7, bone meal at 8.
Composter(i32),
@@ -82,7 +84,7 @@ impl View {
}
}
fn dir_from_name(name: &str) -> Option<Direction> {
pub(super) fn dir_from_name(name: &str) -> Option<Direction> {
Some(match name {
"down" => Direction::Down,
"up" => Direction::Up,
@@ -169,6 +171,7 @@ impl Containers<'_> {
(BlockEntity::Furnace(_), _) => Kind::Furnace,
(BlockEntity::Crafter(_), _) => Kind::Crafter,
(BlockEntity::Brewing(_), _) => Kind::Brewing,
(BlockEntity::ChiseledBookshelf(_), _) => Kind::Bookshelf,
(_, "minecraft:hopper") => Kind::Hopper,
_ => Kind::Generic,
};
@@ -250,6 +253,16 @@ impl Containers<'_> {
_ => false,
};
}
if view.kind == Kind::Bookshelf {
// ListBackedContainer.canPlaceItem: `acceptsItemType` (the books)
// and a free slot, as `getMaxStackSize` is 1.
return self
.items
.item_tags
.get("minecraft:bookshelf_books")
.is_some_and(|m| m.contains(&*stack.item))
&& self.get(view, slot).is_none();
}
if view.kind == Kind::Brewing {
// BrewingStandBlockEntity.canPlaceItem
return match slot {
@@ -399,6 +412,45 @@ pub(super) fn container_signal(
.map_or(0, |v| c.signal(&v))
}
/// `ChiseledBookShelfBlock.getAnalogOutputSignal` and
/// `ShelfBlock.getAnalogOutputSignal`, from the block entity Horizon keeps as
/// it was loaded; `None` for any other block. `direction` points from the
/// block to the comparator.
pub(super) fn shelf_signal(
world: &World,
registry: &'static horizon_world::registry::BlockRegistry,
state: BlockStateId,
pos: BlockPos,
direction: Direction,
) -> Option<i32> {
let info = registry.state(state)?;
let chiseled = info.name == "minecraft:chiseled_bookshelf";
if !chiseled && !info.name.ends_with("_shelf") {
return None;
}
if chiseled {
// The last slot touched, plus one (`lastInteractedSlot` starts at -1).
return Some(match world.block_entities.get(&(pos.x, pos.y, pos.z)) {
Some(BlockEntity::ChiseledBookshelf(b)) => b.last_slot + 1,
_ => 0,
});
}
let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]);
// Only read from the back: a bit for each of the three slots in use.
let facing = info.properties.get("facing").and_then(|f| dir_from_name(f));
if facing.map(Direction::opposite) != Some(direction) {
return Some(0);
}
let items = horizon_client::save::decode_items(tag.as_ref().and_then(|t| t.get("Items")), 3);
Some(
items
.iter()
.enumerate()
.map(|(slot, item)| i32::from(item.is_some()) << slot)
.sum(),
)
}
impl Game<'_> {
fn containers(&self) -> Containers<'_> {
Containers {
@@ -433,6 +485,7 @@ impl Game<'_> {
if pos.1 == super::minecarts::CART_KEY_Y {
return;
}
self.chiseled_bookshelf_synced(pos);
// A double chest's other half changes with it.
let halves: Vec<Pos> = std::iter::once(pos)
.chain(self.chest_other_half(pos))
+12
View File
@@ -547,6 +547,11 @@ pub fn encode_block_entity(
}
}
BlockEntity::Sculk(s) => entries.extend(s.to_nbt()),
// ChiseledBookShelfBlockEntity.saveAdditional.
BlockEntity::ChiseledBookshelf(b) => {
entries.push(("Items", encode_items(&b.items)));
entries.push(("last_interacted_slot", Tag::Int(b.last_slot)));
}
// CampfireBlockEntity.saveAdditional.
BlockEntity::Campfire(c) => {
entries.push(("Items", encode_items(&c.items)));
@@ -785,6 +790,13 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
}
BlockEntity::Sign(sign) => sign.decode(tag),
BlockEntity::Sculk(s) => s.load(tag),
// ChiseledBookShelfBlockEntity.loadAdditional.
BlockEntity::ChiseledBookshelf(b) => {
for (slot, item) in decode_items(tag.get("Items"), 6).into_iter().enumerate() {
b.items[slot] = item;
}
b.last_slot = int("last_interacted_slot").unwrap_or(-1);
}
// CampfireBlockEntity.loadAdditional: missing time arrays stay zeros.
BlockEntity::Campfire(c) => {
for (slot, item) in decode_items(tag.get("Items"), 4).into_iter().enumerate() {
+6
View File
@@ -571,6 +571,12 @@ props! {
orientation = "orientation",
crafting = "crafting",
side_chain = "side_chain",
slot_0_occupied = "slot_0_occupied",
slot_1_occupied = "slot_1_occupied",
slot_2_occupied = "slot_2_occupied",
slot_3_occupied = "slot_3_occupied",
slot_4_occupied = "slot_4_occupied",
slot_5_occupied = "slot_5_occupied",
copper_golem_pose = "copper_golem_pose",
sculk_sensor_phase = "sculk_sensor_phase",
shrieking = "shrieking",
@@ -24,6 +24,44 @@ impl InteractionResult {
}
}
/// `SelectableSlotContainer.getHitSlot`: the slot of a block with `rows` by
/// `columns` slots on its front face (the way it `facing`) that the click at
/// `hit` on `face` of the block at `pos` lands in, if it is the front face.
pub fn hit_slot(
facing: Direction,
face: Direction,
pos: BlockPos,
hit: Vec3,
rows: i32,
columns: i32,
) -> Option<usize> {
if facing != face {
return None;
}
// The location relative to the block in front of the face, which only
// moves the axis the face points along: the others are the block's own.
let (dx, dy, dz) = (
hit.x - f64::from(pos.x),
hit.y - f64::from(pos.y),
hit.z - f64::from(pos.z),
);
let (x, y) = match face {
Direction::North => ((1.0 - dx) as f32, dy as f32),
Direction::South => (dx as f32, dy as f32),
Direction::West => (dz as f32, dy as f32),
Direction::East => ((1.0 - dz) as f32, dy as f32),
Direction::Down | Direction::Up => return None,
};
// getSection
let section = |relative: f32, sections: i32| {
let size = 16.0f32 / sections as f32;
((relative * 16.0f32 / size).floor() as i32).clamp(0, sections - 1)
};
let row = section(1.0 - y, rows);
let column = section(x, columns);
Some((column + row * columns) as usize)
}
/// The interacting player, as far as block behaviour needs it.
#[derive(Clone, Copy, Debug)]
pub struct PlayerContext {
@@ -326,6 +364,27 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
Consume
}
}
Class::ChiseledBookShelf => {
// useItemOn and useWithoutItem agree on what a click takes: no
// slot under it passes, an empty slot consumes it, a book in
// it comes out (the block entity is the game's).
let Some(slot) = hit_slot(b.facing(state), face, pos, hit, 2, 3) else {
return Pass;
};
let occupied = [
p.slot_0_occupied,
p.slot_1_occupied,
p.slot_2_occupied,
p.slot_3_occupied,
p.slot_4_occupied,
p.slot_5_occupied,
];
if table.bool(state, occupied[slot]) {
Success
} else {
Consume
}
}
Class::Bell => {
let click_y = hit.y - f64::from(pos.y);
let proper = axis_of(face) != Axis::Y && click_y <= 0.8124 && {
+1 -1
View File
@@ -137,7 +137,7 @@ mod tests;
pub use buckets::BucketContent;
pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags};
pub use falling::Landing;
pub use interact::{InteractionResult, PlayerContext, PlayerEffect};
pub use interact::{InteractionResult, PlayerContext, PlayerEffect, hit_slot};
pub use pistons::{BlockEventData, MovingPiston};
pub use place::{PlaceContext, PlaceOutcome};
pub use states::{BlockId, PropKey, StateTable};