Fix hand swing prediction for rejected block placements

This commit is contained in:
rdbtCVS
2026-10-22 17:37:42 +01:00
parent 022600481e
commit ecbb0368c5
4 changed files with 222 additions and 27 deletions
+196 -24
View File
@@ -3489,7 +3489,15 @@ impl Game<'_> {
self.predict_use(&changes, seq);
}
if held_block {
self.with_hand(hand, Game::swing_arm);
if reacts
|| held
.as_ref()
.is_some_and(|stack| self.remote_can_place(&hit, stack))
{
self.with_hand(hand, Game::swing_arm);
}
// BlockItem.place returns FAIL when placement is rejected:
// stop this click without trying the item or the other hand.
return true;
}
return reacts;
@@ -3547,7 +3555,11 @@ impl Game<'_> {
/// container, and the blocks it changed. Vanilla's client runs it on its
/// own level first; this runs it on a copy, and `predict_use` keeps the
/// changes it predicts.
fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) {
fn remote_block_reacts(
&mut self,
hit: &super::Hit,
held: Option<&ItemStack>,
) -> (bool, DryUse) {
// Player.isSecondaryUseActive with something in either hand.
let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some();
if self.keys.contains(&KeyCode::ShiftLeft) && hands_full {
@@ -3562,26 +3574,53 @@ impl Game<'_> {
[-1, 0, 0] => Direction::West,
_ => Direction::East,
};
let mut level = DryLevel {
world: &self.world,
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
sounds: Vec::new(),
let player = self.use_context();
self.with_level(|b, level, _| {
let mut level = DryLevel::new(level);
let reacts = b
.use_item_on(
&mut level,
&mut horizon_world::level::Ticks::default(),
horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
player,
held.map(|s| &*s.item),
)
.consumes_action();
(reacts, (level.changed.into_iter().collect(), level.sounds))
})
}
/// Run BlockItem.place on a disposable level before predicting its swing.
/// The real level supplies collision shapes and building-blocking entities;
/// block writes, random draws, scheduled ticks and events stay in the preview.
fn remote_can_place(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool {
if !self.may_build() {
return false;
}
let ctx = horizon_world::level::PlaceContext {
clicked_pos: horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face: horizon_core::geometry::Direction::ALL[face_direction(hit.face) as usize],
hit: Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
inside: hit.face == [0; 3],
yaw: self.yaw,
pitch: self.pitch,
sneaking: self.keys.contains(&KeyCode::ShiftLeft),
item: stack.item.to_string(),
can_use_game_master_blocks: self.can_use_game_master_blocks(),
};
let reacts = self
.res
.behaviours()
.use_item_on(
&mut level,
&mut horizon_world::level::Ticks::default(),
horizon_core::position::BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
horizon_core::geometry::Vec3::new(hit.point[0], hit.point[1], hit.point[2]),
self.use_context(),
held.map(|s| &*s.item),
self.with_level(|b, level, _| {
let mut level = DryLevel::new(level);
matches!(
b.place_block(
&mut level,
&mut horizon_world::level::Ticks::default(),
&ctx
),
horizon_world::level::PlaceOutcome::Placed { .. }
)
.consumes_action();
(reacts, (level.changed.into_iter().collect(), level.sounds))
})
}
/// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether
@@ -4529,7 +4568,7 @@ pub(super) fn input_ordinal(input: Input) -> i32 {
/// The client's world for a guess at what a click does: reads go to the
/// world, writes stay here and are dropped.
struct DryLevel<'w> {
world: &'w horizon_client::world::World,
base: &'w dyn horizon_world::level::LevelAccess,
changed: HashMap<horizon_core::position::BlockPos, BlockStateId>,
random: horizon_core::random::LegacyRandom,
/// The sounds the use plays (a door's creak).
@@ -4559,6 +4598,17 @@ pub(super) fn hand_operated(name: &str) -> bool {
|| name == "lever"
}
impl<'w> DryLevel<'w> {
fn new(base: &'w dyn horizon_world::level::LevelAccess) -> Self {
Self {
base,
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
sounds: Vec::new(),
}
}
}
impl horizon_world::level::LevelAccess for DryLevel<'_> {
fn emit(&mut self, event: horizon_world::level::LevelEvent) {
if let horizon_world::level::LevelEvent::Sound {
@@ -4575,7 +4625,7 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> {
self.changed
.get(&pos)
.copied()
.unwrap_or_else(|| self.world.block(pos.x, pos.y, pos.z))
.unwrap_or_else(|| self.base.block_state(pos))
}
fn set_raw(
&mut self,
@@ -4587,13 +4637,31 @@ impl horizon_world::level::LevelAccess for DryLevel<'_> {
Some(previous)
}
fn is_loaded(&self, pos: horizon_core::position::BlockPos) -> bool {
self.world.loaded(pos.x, pos.z)
self.base.is_loaded(pos)
}
fn min_y(&self) -> i32 {
self.base.min_y()
}
fn max_y(&self) -> i32 {
self.base.max_y()
}
fn block_light(&self, pos: horizon_core::position::BlockPos) -> i32 {
self.base.block_light(pos)
}
fn sky_light(&self, pos: horizon_core::position::BlockPos) -> i32 {
self.base.sky_light(pos)
}
fn sky_darken(&self) -> i32 {
self.base.sky_darken()
}
fn is_unobstructed(&self, pos: horizon_core::position::BlockPos, state: BlockStateId) -> bool {
self.base.is_unobstructed(pos, state)
}
fn random(&mut self) -> &mut horizon_core::random::LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
self.world.game_time
self.base.game_time()
}
}
@@ -4709,6 +4777,110 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_
mod tests {
use super::Game;
#[test]
fn placement_preview_checks_obstruction_without_changing_the_level() {
use super::DryLevel;
use horizon_core::{position::BlockPos, random::LegacyRandom};
use horizon_world::{
level::{
Behaviours, LevelAccess, PlaceContext, PlaceOutcome, Ticks, data::load_registry,
},
registry::BlockStateId,
};
struct Level {
air: BlockStateId,
stone: BlockStateId,
obstructed: bool,
loaded: bool,
ceiling: i32,
}
impl LevelAccess for Level {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
if pos == BlockPos::new(0, 0, 0) {
self.stone
} else {
self.air
}
}
fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option<BlockStateId> {
panic!("preview must not write to the live level");
}
fn is_loaded(&self, _: BlockPos) -> bool {
self.loaded
}
fn max_y(&self) -> i32 {
self.ceiling
}
fn is_unobstructed(&self, pos: BlockPos, _: BlockStateId) -> bool {
assert_eq!(pos, BlockPos::new(0, 1, 0));
!self.obstructed
}
fn random(&mut self) -> &mut LegacyRandom {
panic!("preview must not advance the live level's random source");
}
fn game_time(&self) -> i64 {
0
}
}
// As with the LAN tests, prepared game resources are optional locally.
let resources = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION);
if !resources.join("block-behaviours.json").exists() {
return;
}
let registry = load_registry(&resources).unwrap();
let behaviours = Behaviours::load(&registry, &resources).unwrap();
let mut base = Level {
air: registry.default_state("minecraft:air").unwrap(),
stone: registry.default_state("minecraft:stone").unwrap(),
obstructed: false,
loaded: true,
ceiling: 320,
};
for item in [
"minecraft:stone",
"minecraft:oak_slab",
"minecraft:oak_door",
// GrowingPlantHeadBlock.getStateForPlacement draws a random age.
"minecraft:twisting_vines",
] {
let ctx = PlaceContext {
clicked_pos: BlockPos::new(0, 0, 0),
face: horizon_core::geometry::Direction::Up,
hit: horizon_core::geometry::Vec3::new(0.5, 1.0, 0.5),
inside: false,
yaw: 0.0,
pitch: 45.0,
sneaking: false,
item: item.into(),
can_use_game_master_blocks: false,
};
for (obstructed, loaded, ceiling) in [
(false, true, 320),
(true, true, 320),
(false, false, 320),
(false, true, 1),
] {
base.obstructed = obstructed;
base.loaded = loaded;
base.ceiling = ceiling;
let valid = !obstructed && loaded && ceiling > 1;
let mut preview = DryLevel::new(&base);
let outcome = behaviours.place_block(&mut preview, &mut Ticks::default(), &ctx);
assert_eq!(
matches!(outcome, PlaceOutcome::Placed { .. }),
valid,
"{item}, obstructed={obstructed}, loaded={loaded}, ceiling={ceiling}"
);
assert_eq!(preview.changed.is_empty(), !valid);
assert_eq!(base.block_state(BlockPos::new(0, 1, 0)), base.air);
}
}
}
#[test]
fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() {
// InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand.
@@ -20,6 +20,7 @@ struct Cells {
cells: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
obstructed: bool,
}
impl LevelAccess for Cells {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
@@ -37,6 +38,9 @@ impl LevelAccess for Cells {
fn game_time(&self) -> i64 {
0
}
fn is_unobstructed(&self, _pos: BlockPos, _state: BlockStateId) -> bool {
!self.obstructed
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -68,6 +72,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
cells,
air,
random: LegacyRandom::new(case["seed"].as_i64().unwrap()),
obstructed: case["obstructed"].as_bool().unwrap_or(false),
};
let mut ticks = Ticks::new(0);
for x in -2..=2 {
@@ -27,7 +27,7 @@ import net.minecraft.world.phys.shapes.CollisionContext;
/**
* Native BlockItem placement-state selection (BlockPlaceContext resolution,
* updatePlacementContext and getPlacementState) over generated neighbourhoods.
* Entities never obstruct; nothing is written to the world.
* Entity obstruction can be scripted; nothing is written to the world.
*/
public final class VanillaBlockPlacementOracle {
static Object unsafe;
@@ -67,6 +67,7 @@ public final class VanillaBlockPlacementOracle {
static final class World extends net.minecraft.server.level.ServerLevel {
Map<BlockPos, BlockState> cells;
RandomSource random;
boolean obstructed;
World() {
super(null, null, null, null, null, null, false, 0L, List.of(), false);
}
@@ -77,7 +78,7 @@ public final class VanillaBlockPlacementOracle {
@Override public RandomSource getRandom() { return random; }
@Override public int getMinY() { return -64; }
@Override public int getHeight() { return 384; }
@Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return true; }
@Override public boolean isUnobstructed(BlockState state, BlockPos pos, CollisionContext context) { return !obstructed; }
@Override public boolean isUnobstructed(Entity entity) { return true; }
@Override public void scheduleTick(BlockPos pos, Block block, int delay) { }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); }
@@ -116,6 +117,7 @@ public final class VanillaBlockPlacementOracle {
world.cells.put(new BlockPos(c.get(0).getAsInt(), c.get(1).getAsInt(), c.get(2).getAsInt()), Block.stateById(c.get(3).getAsInt()));
}
world.random = new LegacyRandomSource(f.get("seed").getAsLong());
world.obstructed = f.has("obstructed") && f.get("obstructed").getAsBoolean();
var player = make(FakePlayer.class);
player.world = world;
player.yaw = f.get("yaw").getAsFloat();
+17 -1
View File
@@ -68,6 +68,22 @@ def generate(resources, count, seed):
return cases
def obstruction_cases(resources):
"""Placement failures must not predict a hand swing.
Exercise BlockItem.canPlace's entity-obstruction gate with the same
otherwise valid placements, including partial shapes and two-block items.
"""
facts = json.loads((resources / 'facts.json').read_text())
states = {s[0]: i for i, s in reversed(list(enumerate(facts['states'])))}
stone = states['minecraft:stone']
for item in ['minecraft:stone', 'minecraft:oak_slab', 'minecraft:oak_stairs',
'minecraft:oak_door', 'minecraft:torch']:
for obstructed in [False, True]:
yield dict(seed=0, item=item, pos=[0, 0, 0], face=1, hit=[0.5, 1.0, 0.5],
yaw=0, pitch=45, sneak=False, cells=[[0, 0, 0, stone]], obstructed=obstructed)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=20000)
@@ -77,7 +93,7 @@ def main():
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'level-place-parity'
work.mkdir(parents=True, exist_ok=True)
cases = generate(resources, args.count, args.seed)
cases = list(obstruction_cases(resources)) + generate(resources, args.count, args.seed)
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)