Merge remote-tracking branch 'origin/fix/guest-predicts-door-use' into integ/b5-lan-rest

# Conflicts:
#	tools/lan_e2e.py
This commit is contained in:
Ludovic Marie
2026-10-22 06:17:27 +02:00
5 changed files with 187 additions and 10 deletions
+7
View File
@@ -158,6 +158,9 @@ pub struct Audio {
/// Positional sounds played since the last drain, kept while the world
/// is open to the network so guests hear them too.
pub capture: Option<Vec<(String, [f64; 3], f32, f32)>>,
/// How many times each positional sound played (the control socket's `status`),
/// with or without an audio device.
pub heard: std::collections::BTreeMap<String, u32>,
}
fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
use symphonia::core::{
@@ -591,6 +594,7 @@ impl Audio {
random: LegacyRandom::new(crate::sound_engine::unique_seed()),
source_override: None,
capture: None,
heard: Default::default(),
}
}
#[cfg(not(feature = "audio"))]
@@ -733,6 +737,9 @@ impl Audio {
if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) {
capture.push((event.to_owned(), at, volume, pitch));
}
if at.is_some() {
*self.heard.entry(event.to_owned()).or_default() += 1;
}
self.sync_volumes();
let event = crate::sound_events::normalize(event);
let source = self
@@ -912,6 +912,7 @@ impl Game<'_> {
status["pending_uploads"] = self.pending_uploads.len().into();
status["destroying"] = json!(destroying);
status["physical_keys"] = json!(physical_keys);
status["heard"] = json!(self.audio.heard);
// Boats, minecarts, armor stands, item frames and paintings.
status["objects"] = json!(self.objects_status());
// Primed TNT, falling blocks, projectiles, tridents and end crystals.
@@ -832,6 +832,8 @@ impl Game<'_> {
],
};
let hand = if p.hand == 1 { Hand::Off } else { Hand::Main };
let logged = self.world.block_log.as_ref().map_or(0, Vec::len);
let heard = self.audio.capture.as_ref().map_or(0, Vec::len);
let swung = self.as_guest(host, conn, |g| {
g.forced_hit = Some(hit);
g.guest_use = Some(GuestUse::OnBlock(hand));
@@ -842,6 +844,7 @@ impl Game<'_> {
g.swings_started != swings
});
self.lan_swing_back(host, conn, swung);
self.guest_use_sounds(host, conn, logged, heard);
// The client predicted a result: correct it with what really is.
for pos in [
p.pos,
@@ -2005,6 +2008,33 @@ impl Game<'_> {
}
}
/// `level.playSound(player, ...)` of a guest's use it predicted (`remote::hand_operated`
/// blocks only, as the guest decides): the others hear it now, the guest already did.
fn guest_use_sounds(&mut self, host: &mut LanHost, conn: u32, logged: usize, heard: usize) {
let changed: Vec<(i32, i32, i32)> = self
.world
.block_log
.as_ref()
.map_or(&[][..], |log| log.get(logged..).unwrap_or(&[]))
.to_vec();
let facts = self.res.facts();
if changed.is_empty()
|| !changed.iter().all(|&(x, y, z)| {
super::remote::hand_operated(&facts.get(self.world.block(x, y, z)).name)
})
{
return;
}
let Some(capture) = self.audio.capture.as_mut() else {
return;
};
let sounds: Vec<_> = capture.drain(heard.min(capture.len())..).collect();
for (name, at, volume, pitch) in sounds {
let source = horizon_client::settings::sound_source(&name) as i32;
host.hub.sound(&name, at, volume, pitch, source, Some(conn));
}
}
/// Positional sounds and level events of the tick, for the guests.
pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) {
let sounds = self.audio.capture.take().unwrap_or_default();
+99 -7
View File
@@ -3244,7 +3244,11 @@ impl Game<'_> {
.and_then(|h| self.res.items().get(&h.item))
.is_some_and(|i| i.block.is_some());
if let Some(hit) = self.pick() {
let reacts = hand == Hand::Main && self.remote_block_reacts(&hit, held.as_ref());
let (reacts, changes) = if hand == Hand::Main {
self.remote_block_reacts(&hit, held.as_ref())
} else {
(false, DryUse::default())
};
let seq = self.next_sequence();
let cursor = [
(hit.point[0] - f64::from(hit.pos[0])) as f32,
@@ -3270,6 +3274,9 @@ impl Game<'_> {
r.use_target = Some(hit.pos);
r.placing = Some((target, ticks));
}
if reacts {
self.predict_use(&changes, seq);
}
if held_block {
self.with_hand(hand, Game::swing_arm);
return true;
@@ -3279,15 +3286,61 @@ impl Game<'_> {
false
}
/// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the
/// use changed on this client's level at once, each kept as predicted
/// under the use's sequence until the server acknowledges it (a use the
/// server refused goes back). Only the blocks a hand opens or flips: a
/// wooden or copper door, trapdoor or fence gate, a lever or a button;
/// whatever else the use changes waits for the server.
fn predict_use(&mut self, (changes, sounds): &DryUse, seq: i32) {
let facts = self.res.facts();
let predicted = |state: BlockStateId| hand_operated(&facts.get(state).name);
if changes.is_empty()
|| !changes
.iter()
.all(|(p, s)| predicted(*s) && predicted(self.world.block(p.x, p.y, p.z)))
{
return;
}
for &(p, state) in changes {
let pos = [p.x, p.y, p.z];
let before = self.world.block(p.x, p.y, p.z);
// BlockStatePredictionHandler.retainKnownServerState.
if let Some(r) = self.remote.as_mut() {
r.predictions
.entry(pos)
.and_modify(|e| e.0 = seq)
.or_insert((seq, before.0 as i32));
}
self.set_block(pos, state.0 as i32);
}
// `level.playSound(player, ...)`: the clicker hears it from its own use; the
// server sends it to the others only.
for (pos, sound, volume, pitch) in sounds {
let at = [
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 0.5,
f64::from(pos.z) + 0.5,
];
let name = if sound.contains(':') {
sound.to_string()
} else {
format!("minecraft:{sound}")
};
self.audio.play(&name, Some(at), *volume, *pitch);
}
}
/// Whether the block hit takes a main-hand right click with `held`
/// (`BlockState.useItemOn`, then `useWithoutItem`): a door, a button, a
/// container. Vanilla's client runs it on its own level first; this runs
/// it on a copy that keeps no change.
fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> bool {
/// 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) {
// 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 {
return false;
return (false, DryUse::default());
}
use horizon_core::geometry::Direction;
let face = match hit.face {
@@ -3302,8 +3355,10 @@ impl Game<'_> {
world: &self.world,
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
sounds: Vec::new(),
};
self.res
let reacts = self
.res
.behaviours()
.use_item_on(
&mut level,
@@ -3314,7 +3369,8 @@ impl Game<'_> {
self.use_context(),
held.map(|s| &*s.item),
)
.consumes_action()
.consumes_action();
(reacts, (level.changed.into_iter().collect(), level.sounds))
}
/// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether
@@ -4243,9 +4299,45 @@ struct DryLevel<'w> {
world: &'w horizon_client::world::World,
changed: HashMap<horizon_core::position::BlockPos, BlockStateId>,
random: horizon_core::random::LegacyRandom,
/// The sounds the use plays (a door's creak).
sounds: Vec<DrySound>,
}
type DrySound = (
horizon_core::position::BlockPos,
std::sync::Arc<str>,
f32,
f32,
);
/// What a use on the dry level changed, and the sounds it played.
type DryUse = (
Vec<(horizon_core::position::BlockPos, BlockStateId)>,
Vec<DrySound>,
);
/// The blocks a guest's hand flips that its use predicts (and hears at once): a wooden or
/// copper door, trapdoor or fence gate, a lever or a button. An iron door or trapdoor has
/// no hand use.
pub(super) fn hand_operated(name: &str) -> bool {
let name = name.trim_start_matches("minecraft:");
((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_"))
|| name.ends_with("_fence_gate")
|| name.ends_with("_button")
|| name == "lever"
}
impl horizon_world::level::LevelAccess for DryLevel<'_> {
fn emit(&mut self, event: horizon_world::level::LevelEvent) {
if let horizon_world::level::LevelEvent::Sound {
pos,
sound,
volume,
pitch,
} = event
{
self.sounds.push((pos, sound, volume, pitch));
}
}
fn block_state(&self, pos: horizon_core::position::BlockPos) -> BlockStateId {
self.changed
.get(&pos)
+50 -3
View File
@@ -56,6 +56,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
its crafting grid and gathers a stack with a double click; the server has each.
- sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it
gets up with Escape, and once the host sleeps too the night ends and both wake.
- predict: with the host frozen, the oak door the guest opens opens on the guest's screen at once (its
prediction) and creaks there at once, stays open once the server answers, and each side hears
it once; an iron door stays shut (#869).
- push: a cow standing in the guest pushes it just clear of the cow (the guest's own client
pushes it, as in vanilla), not ever faster across the ground.
- eat: holding right click with bread, the guest's own screen plays the eating (the item in use
@@ -127,7 +130,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', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth']
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']
class Game:
@@ -1335,6 +1338,50 @@ def check_sleep(host, guest, out):
assert lying['host'] and lying['guest'], f'a sleeping player is drawn standing: {detail}'
assert not lying['after'], f'a player up again is still drawn lying: {detail}'
return detail
def check_predict(host, guest, out):
# MultiPlayerGameMode.useItemOn under startPrediction (#869): the guest's door opens on its own screen
# at once, with the host (the server) frozen, and the server's answer later agrees; an iron door
# (no hand use) stays shut on both sides.
guest('command', command='gamemode survival')
guest('command', command='clear @s')
x, y, z = (int(v // 1) for v in pos_of(guest))
wood, iron = (x - 1, y, z + 2), (x + 1, y, z + 2)
for (bx, by, bz), kind in ((wood, 'oak_door'), (iron, 'iron_door')):
for half, dy in (('lower', 0), ('upper', 1)):
host('command', command=f'setblock {bx} {by + dy} {bz} minecraft:{kind}[facing=north,hinge=right,half={half}]')
guest.wait(20)
state = lambda game, at: game.raw('block', *at)['state']
seen = {}
creaks = lambda game: sum(n for s, n in game('status')['heard'].items() if 'door' in s)
heard = {'guest': creaks(guest), 'host': creaks(host)}
os.kill(host.pid, signal.SIGSTOP)
try:
guest.raw('interact', *wood)
seen['guest_frozen'] = (state(guest, wood), state(guest, (wood[0], wood[1] + 1, wood[2])))
# level.playSound(player, ...): the clicker hears its own door at once.
seen['guest_heard_frozen'] = creaks(guest) - heard['guest']
guest.raw('interact', *iron)
seen['guest_iron_frozen'] = state(guest, iron)
finally:
os.kill(host.pid, signal.SIGCONT)
guest.wait(20)
seen['guest_after'] = state(guest, wood)
seen['host_after'] = state(host, wood)
seen['iron_after'] = (state(guest, iron), state(host, iron))
# ... and not a second time from the server; the host hears it once.
seen['heard_after'] = {'guest': creaks(guest) - heard['guest'], 'host': creaks(host) - heard['host']}
guest.shot(out, 'predict')
for (bx, by, bz) in (wood, iron):
host('command', command=f'fill {bx} {by} {bz} {bx} {by + 1} {bz} minecraft:air')
assert all('open=true' in s for s in seen['guest_frozen']), f'the door waited for the server: {seen}'
assert 'open=true' in seen['guest_after'] and 'open=true' in seen['host_after'], f'the door did not stay open: {seen}'
assert 'open=false' in seen['guest_iron_frozen'], f'the guest opened an iron door by hand: {seen}'
assert all('open=false' in s for s in seen['iron_after']), f'an iron door opened: {seen}'
assert seen['guest_heard_frozen'] == 1 and seen['heard_after'] == {'guest': 1, 'host': 1}, \
f'the door is not heard once on each side: {seen}'
return seen
def check_push(host, guest, out):
guest('command', command='gamemode survival')
x, y, z = (int(v // 1) + 0.5 for v in pos_of(guest))
@@ -2039,7 +2086,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast,
'light': check_light, 'plates': check_plates,
'swings': check_swings, 'cracks': check_cracks,
'time': check_time, 'growth': check_growth, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows}
'time': check_time, 'growth': check_growth, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict}
def run(ctl, out, resources, checks):
@@ -2048,7 +2095,7 @@ def run(ctl, out, resources, checks):
host.d.env['HORIZON_SERVER_THREAD'] = '1'
results = {}
try:
host('launch', wait=False, offscreen=sys.platform == 'darwin')
host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid']
# Guests' commands need the world's Allow Commands as well as the LAN's (#372): a creative
# world has them; everyone plays in survival.
host.raw('open', 'Lan', 5, 'creative')