diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8eb67d134..a74f1677e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8084,40 +8084,48 @@ impl Game<'_> { self.stats.reset("custom", "minecraft:time_since_rest"); } fn wake_up(&mut self) { + if self.remote.is_some() { + // InBedChatScreen.sendWakeUp: the server wakes the player. + self.remote_stop_sleeping(); + return; + } self.sleeping = None; self.sleep_timer = 100; } fn tick_sleep(&mut self) { self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); - let Some(head) = self.sleeping else { - return; - }; - if self.keys.contains(&KeyCode::ShiftLeft) - || self - .player - .as_ref() - .is_none_or(|p| p.health.dead_or_dying()) - { - self.wake_up(); - return; + if let Some(head) = self.sleeping { + if self.keys.contains(&KeyCode::ShiftLeft) + || self + .player + .as_ref() + .is_none_or(|p| p.health.dead_or_dying()) + { + self.wake_up(); + return; + } + if let Some(p) = self.player.as_mut() { + p.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); + p.velocity = Vec3::ZERO; + } } - if let Some(p) = self.player.as_mut() { - p.position = Vec3::new( - f64::from(head[0]) + 0.5, - f64::from(head[1]) + 0.5625, - f64::from(head[2]) + 0.5, - ); - p.velocity = Vec3::ZERO; - } - // ServerLevel: once everyone has slept 100 ticks, skip to morning and clear weather. - if self.sleep_timer >= 100 { + // ServerLevel.tick: once enough of the players have slept 100 ticks, + // skip to morning, clear the weather and wake everyone. + if self.enough_slept() { let t = self.world.day_time; self.world.day_time = t + 24000 - t.rem_euclid(24000); self.world.weather.raining = false; self.world.weather.thundering = false; self.world.weather.rain_time = 0; self.world.weather.thunder_time = 0; - self.wake_up(); + if self.sleeping.is_some() { + self.wake_up(); + } + self.wake_guests(); } } fn creative_origin(batch: &HudBatch) -> (f32, f32) { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 8e956373e..0a6f6cc95 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -466,6 +466,8 @@ impl Game<'_> { }), "dimension": self.dim.id(), "gamemode": format!("{:?}", self.mode).to_lowercase(), + // The bed (its head) the player sleeps in. + "sleeping": self.sleeping, "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, "weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering }, "paused": self.pause, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 78588cf4f..156659ab3 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -370,6 +370,7 @@ impl Game<'_> { "loaded": g.loaded, "game_mode": g.game_mode, "sneaking": g.sneaking, + "sleeping": g.bed, "health": g.health, // FoodData: food level, saturation and exhaustion. "food": [ diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 9281cc3a1..a21fe88da 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -172,6 +172,16 @@ impl Game<'_> { self.right = play.using.is_some() || self.using.is_some(); let riding = self.riding.take(); let host_station = self.station.take(); + // The guest's bed, sleep counter and respawn point; the host's + // respawn point, anchor and action bar stay theirs. + let sleeping = std::mem::replace(&mut self.sleeping, g.bed); + let sleep_timer = std::mem::replace(&mut self.sleep_timer, g.sleep_timer); + let spawn = std::mem::replace( + &mut self.spawn, + g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])), + ); + let respawn = (self.respawn_config.take(), self.level.spawn); + let message = self.message.take(); // The guest's own ender inventory; one the host has open goes back // into the host's while the guest acts. let host_ender = self.ender_open; @@ -203,6 +213,12 @@ impl Game<'_> { let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3; self.craft_grid = craft_grid; let opened_station = std::mem::replace(&mut self.station, host_station); + let bed = std::mem::replace(&mut self.sleeping, sleeping); + let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer); + let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]); + (self.respawn_config, self.level.spawn) = respawn; + // ServerPlayer.displayClientMessage(_, true): the guest's action bar. + let guest_message = std::mem::replace(&mut self.message, message); self.riding = riding; self.left = left; self.right = right; @@ -220,6 +236,15 @@ impl Game<'_> { self.mount_menu = host_mount_menu; self.keys = host_keys; let g = &mut host.hub.guests[i]; + let fell_asleep = bed.is_some() && g.bed.is_none(); + (g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn); + g.sleeping = g.bed.is_some(); + if let Some((text, _)) = guest_message { + g.send(&C::SystemChat(play::SystemChat { + content: literal(&text), + overlay: true, + })); + } std::mem::swap(&mut self.ender_items, &mut g.ender_items); std::mem::swap(&mut self.adv.progress, &mut g.advancements); std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed); @@ -269,6 +294,19 @@ impl Game<'_> { } } let g = &mut host.hub.guests[i]; + if let Some(head) = g.bed.filter(|_| fell_asleep) { + // LivingEntity.startSleeping: in the bed, still. + let at = [ + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ]; + g.position = at; + if let Some(m) = g.motion.as_mut() { + m.position = Vec3::new(at[0], at[1], at[2]); + m.velocity = Vec3::ZERO; + } + } if new_mode != g.game_mode { let conn = g.conn; host.hub.set_game_mode(conn, new_mode); @@ -966,10 +1004,19 @@ impl Game<'_> { } fn guest_respawn(&mut self, host: &mut LanHost, conn: u32) { - let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; }; + // The guest's own bed, else the world spawn: never the host's bed. + let world = self + .level + .world_spawn + .map(|[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]); + let spawn = host.hub.guests[i] + .spawn + .or(world) + .or(self.spawn.map(|s| [s.x, s.y, s.z])) + .unwrap_or([0.5, 80.0, 0.5]); if !host.hub.guests[i].dead { return; } @@ -1041,6 +1088,7 @@ impl Game<'_> { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { continue; }; + self.guest_sleep_tick(host, gi); if host.hub.guests[gi].dead || self.on_server_trip(conn) { continue; } @@ -1106,6 +1154,62 @@ impl Game<'_> { } } + /// `Player.tick`'s sleep counter, and `LivingEntity.tick`'s wake-up of a + /// sleeper who died or whose bed is gone. + fn guest_sleep_tick(&mut self, host: &mut LanHost, gi: usize) { + let g = &mut host.hub.guests[gi]; + g.sleep_timer = super::tick_sleep_timer(g.sleep_timer, g.bed.is_some()); + if let Some(head) = g.bed { + let block = self.world.block(head[0], head[1], head[2]); + let bed = self.res.facts.get(block).name.ends_with("_bed"); + if g.dead || g.health <= 0.0 || !bed { + host.hub.wake(gi); + } + } + } + + /// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the + /// host's player and the guests: of the players not in spectator mode, + /// players_sleeping_percentage of them (at least one) are in bed, and as + /// many have slept 100 ticks. + pub(super) fn enough_slept(&self) -> bool { + let (mut active, mut sleeping, mut deep) = (0i64, 0i64, 0i64); + let mut count = |in_bed: bool, timer: u32| { + active += 1; + if in_bed { + sleeping += 1; + if timer >= 100 { + deep += 1; + } + } + }; + if self.player.is_some() && !self.spectator() { + count(self.sleeping.is_some(), self.sleep_timer); + } + if let Some(host) = self.lan.as_ref() { + for g in host + .hub + .guests + .iter() + .filter(|g| g.placed && !g.spectator()) + { + count(g.bed.is_some(), g.sleep_timer); + } + } + let percent = i64::from(self.ui.rules.int("players_sleeping_percentage").max(0)); + let needed = ((active * percent + 99) / 100).max(1); + sleeping >= needed && deep >= needed + } + + /// `ServerLevel.wakeUpAllPlayers` for the guests. + pub(super) fn wake_guests(&mut self) { + if let Some(host) = self.lan.as_mut() { + for i in 0..host.hub.guests.len() { + host.hub.wake(i); + } + } + } + /// `PlayerList.broadcastSystemMessage` of the advancements guests made /// (their own actions, commands and ticks). fn announce_guest_advancements(&mut self, host: &mut LanHost) { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 6e4880bed..9d19947e7 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -807,6 +807,7 @@ impl Game<'_> { 0 => { if me { self.sleeping = None; + self.sleep_timer = 100; } return; } @@ -1327,6 +1328,18 @@ impl Game<'_> { } } } + // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this + // player lies down in the bed, or gets up. + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + for (index, _, value) in &p.values { + if let (14, Value::OptPos(bed)) = (index, value) { + if bed.is_some() && self.sleeping.is_none() { + self.sleep_timer = 0; + } + self.sleeping = *bed; + } + } + } for (index, _, value) in &p.values { if *index == ITEM_ENTITY_ITEM && let Value::Item(stack) = value @@ -2209,6 +2222,8 @@ impl Game<'_> { self.tick_hand(); self.tick_particles(); self.tick_client_effects(); + // Player.tick's sleep counter (the darkening and the wake-up fade). + self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); let ghast_collisions = self.happy_ghast_player_collisions(); let Some(player) = self.player.as_mut() else { return Ok(()); @@ -2260,7 +2275,15 @@ impl Game<'_> { ); player.yaw = self.yaw; let dead = self.screen == Screen::Dead; - if !dead { + // LivingEntity.isImmobile: a sleeper lies still in the bed. + if let Some(head) = self.sleeping { + player.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); + player.velocity = Vec3::ZERO; + } else if !dead { MotionWorld { entities: &ghast_collisions, player, @@ -3249,6 +3272,15 @@ impl Game<'_> { .ok()?; Some((rows, r.menu_title.clone().unwrap_or_default())) } + /// ServerboundPlayerCommandPacket STOP_SLEEPING. + pub(super) fn remote_stop_sleeping(&mut self) { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 0, + data: 0, + })); + } pub(super) fn remote_respawn(&mut self) { self.send(S::ClientCommand(play::ClientCommand { action: 0 })); } diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 545bb6ace..ea12c2edb 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -69,6 +69,14 @@ pub struct Guest { pub fall_flying: bool, pub flying: bool, pub sleeping: bool, + /// The bed (its head) the player sleeps in (`LivingEntity.getSleepingPos`), + /// `Player.sleepCounter`, and the bed last told to the player itself. + pub bed: Option<[i32; 3]>, + pub sleep_timer: u32, + pub sent_bed: Option<[i32; 3]>, + /// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`), + /// None for the world spawn. + pub spawn: Option<[f64; 3]>, /// Pending ClientboundPlayerPositionPacket id; movement is ignored until /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). pub awaiting_teleport: Option<(i32, [f64; 3])>, @@ -204,6 +212,10 @@ impl Guest { fall_flying: false, flying: false, sleeping: false, + bed: None, + sleep_timer: 0, + sent_bed: None, + spawn: None, awaiting_teleport: None, teleport_counter: 0, teleport_tick: 0, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 1b0d8229a..b18187835 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1515,10 +1515,44 @@ impl Hub { } } + /// ServerPlayer.stopSleepInBed: the wake-up animation goes to the player + /// and those around, the pose is standing again and the sleep counter + /// starts the wake-up fade (100). + pub fn wake(&mut self, i: usize) { + let g = &mut self.guests[i]; + if g.bed.take().is_none() && !g.sleeping { + return; + } + g.sleeping = false; + g.sleep_timer = 100; + let (id, at) = (g.entity_id, g.position); + // ClientboundAnimatePacket.WAKE_UP. + self.broadcast_near( + at, + 128.0, + &C::Animate(play::Animate { id, action: 0 }), + None, + ); + } + // ---- per-player state ------------------------------------------------ /// ServerPlayer.doTick: health, food, experience and the inventory menu. fn sync_player_state(&mut self, i: usize) { + // LivingEntity.startSleeping / stopSleeping: the pose and the bed go + // to the player too (its client lies down in the bed from them). + let g = &mut self.guests[i]; + if g.bed != g.sent_bed { + g.sent_bed = g.bed; + let pose = if g.bed.is_some() { 2 } else { 0 }; + g.send(&C::SetEntityData(play::SetEntityData { + id: g.entity_id, + values: vec![ + (6, serializer::POSE, Value::Id(pose)), + (14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(g.bed)), + ], + })); + } // ServerEntity.sendDirtyEntityData on the player's first tick: the // health its creation set is still dirty, and goes to the player too. if self.guests[i].sent_health.is_none() { @@ -1767,7 +1801,8 @@ impl Hub { 1 => self.guests[i].sprinting = true, 2 => self.guests[i].sprinting = false, 6 => self.guests[i].fall_flying = true, - 0 => self.guests[i].sleeping = false, + // STOP_SLEEPING. + 0 => self.wake(i), _ => {} }, S::Chat(c) => { diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 44b269a8f..b6aea0f84 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -69,6 +69,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); guest.selected = (level.selected_slot.max(0) as usize).min(8); + guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); guest.dimension = match level.dimension.as_str() { @@ -129,6 +130,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; level.selected_slot = guest.selected as i32; + level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]); level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); level.recipe_book = guest.recipe_book.clone(); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 38674d639..923f7059a 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -34,6 +34,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - clicks: with real mouse presses (not click-slot, which skips the screen's press and drag handling), the guest puts a stack into a chest and a furnace, drags planks across 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. Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -65,7 +67,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', 'containers', 'feedback', 'commands', 'recipes', 'trials', 'clicks', 'effects', 'portals'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'effects', 'portals'] class Game: @@ -913,12 +915,60 @@ def check_trials(host, guest, out): return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)} +def bed_at(game, foot): + """A bed whose foot is at `foot`, its head one block east.""" + x, y, z = foot + game('command', command=f'setblock {x} {y} {z} minecraft:red_bed[facing=east,part=foot]') + game('command', command=f'setblock {x + 1} {y} {z} minecraft:red_bed[facing=east,part=head]') + return [x + 1, y, z] + + +def check_sleep(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + host('command', command='time set midnight') + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + guest_bed = bed_at(guest, (gx, gy, gz + 2)) + host_bed = bed_at(host, (hx, hy, hz + 2)) + guest.wait(10) + guest.raw('interact', *guest_bed) + guest.wait(10) + asleep = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), + 'server': host.raw('lan', 'status')['guests'][0].get('sleeping')} + guest.shot(out, 'sleep-guest') + # Alone in bed: still night 120 ticks later (everyone must sleep). + guest.wait(120) + night = host('state')['time']['time_of_day'] + # Escape gets the guest up (InBedChatScreen), then back to bed. + guest.raw('key', 'esc', 'tap') + guest.wait(10) + up = guest('state').get('sleeping') + guest.raw('interact', *guest_bed) + host.raw('interact', *host_bed) + host.wait(130) + after = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), + 'time': host('state')['time']['time_of_day']} + guest.shot(out, 'sleep-morning') + for at in (guest_bed, host_bed): + guest('command', command=f'fill {at[0] - 1} {at[1]} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air') + host('command', command='time set day') + detail = {'asleep': asleep, 'night': night, 'up': up, 'after': after} + assert asleep['guest'] == guest_bed and asleep['server'] == guest_bed, f'the guest is not in its bed: {detail}' + assert asleep['host'] is None, f'the guest\'s bed put the host to sleep: {detail}' + assert 13000 < night < 23000, f'one of two players asleep ended the night: {detail}' + assert up is None, f'Escape did not get the guest up: {detail}' + assert after['guest'] is None and after['host'] is None and after['time'] < 1000, f'no morning: {detail}' + return detail + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, - 'effects': check_effects, 'portals': check_portals, 'clicks': check_clicks} + 'effects': check_effects, 'portals': check_portals, 'clicks': check_clicks, + 'sleep': check_sleep} def run(ctl, out, resources, checks):