From 0e36cb4d7a913033a4b179dd03c0d498a0a11579 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:11:22 +0200 Subject: [PATCH] Beds: respawning checks the bed and stands up beside it, else the world spawn A bed sets the respawn point as vanilla's ServerPlayer.startSleepInBed does (once in reach, day or night): a RespawnConfig at the bed's head with the player's yaw, not forced; straw beds never set it (straw_bed_rule). Respawning resolves it through findRespawnAndUseSpawnBlock, which now handles beds: AbstractBedBlock.findStandUpPosition (beside the bed on the side away from the yaw it was set from, around it, then on it; bunk beds too) through DismountHelper, facing the bed. A bed that is gone or boxed in sends the player to the world spawn with "You have no home bed or charged respawn anchor, or it was obstructed", and the point is forgotten: in the window's world, on the server thread and for LAN guests. Leaving the End goes to the bed too (not using it up). Saves keep a bed as the player's `respawn` (resolved through its block when loaded), and a `spawnpoint` in the Overworld as forced. A fallback that is the world spawn follows `setworldspawn` with a bed or anchor set. tools/test_use_item_on_parity.py: respawn cases at a bed's head set from some yaw (intact, bunk, only the foot left or gone, crowded), against vanilla's real findRespawnAndUseSpawnBlock; 4000/4000 and 12000/12000 on two seeds. lan_e2e `beds`: intact, gone and boxed in, host and guest. Fixes #1308 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 42 +++++--- crates/horizon-client/src/game/commands.rs | 7 +- .../src/game/dispense_fixture.rs | 12 +-- crates/horizon-client/src/game/end.rs | 21 +++- crates/horizon-client/src/game/lan_actions.rs | 34 ++++++- .../horizon-client/src/game/respawn_anchor.rs | 99 ++++++++++++++++++- .../horizon-client/src/game/server_travel.rs | 31 ++++-- crates/horizon-client/src/save.rs | 18 +++- .../parity/VanillaDispenserOracle.java | 3 +- tools/lan_e2e.py | 65 +++++++++++- tools/test_use_item_on_parity.py | 56 ++++++++++- 11 files changed, 335 insertions(+), 53 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 40a108d40..af495c98f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9146,31 +9146,41 @@ impl Game<'_> { } else { pos }; - self.spawn = Some(Vec3::new( - f64::from(head[0]) + 0.5, - f64::from(head[1]) + 0.6, - f64::from(head[2]) + 0.5, - )); - // The bed replaces a respawn anchor. - self.respawn_config = None; - self.level.spawn = Some([ - f64::from(head[0]), - f64::from(head[1]) + 1.0, - f64::from(head[2]), - ]); let dist = ((p.position.x - f64::from(head[0]) - 0.5).powi(2) + (p.position.z - f64::from(head[2]) - 0.5).powi(2)) .sqrt(); - if !night { + if dist > 3.0 { self.message = Some(( - "You can sleep only at night or during thunderstorms".into(), + "You may not rest now; the bed is too far away".into(), Instant::now(), )); return; } - if dist > 3.0 { + // In reach (bedInRange), day or night: setRespawnPosition( + // RespawnConfig(the head, the player's yaw), not forced). It replaces + // an anchor or a spawnpoint; respawning checks the bed is still there + // and finds where to stand up (findRespawnAndUseSpawnBlock). + // Straw beds never set it (`straw_bed_rule`). + if self.bed_sets_spawn(state) { + self.respawn_config = Some(respawn_anchor::RespawnConfig::wrapped( + self.dim, head, p.yaw, false, + )); + // The fallback becomes the world spawn: a guest's is none of its + // own, so it follows `setworldspawn`. + self.spawn = if self.lan_acting.is_some() { + None + } else { + self.level + .world_spawn + .map(|[x, y, z]| { + Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5) + }) + .or(self.spawn) + }; + } + if !night { self.message = Some(( - "You may not rest now; the bed is too far away".into(), + "You can sleep only at night or during thunderstorms".into(), Instant::now(), )); return; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index d4ff91a49..fb1e57ad6 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2340,10 +2340,11 @@ impl Game<'_> { // LevelData.setRespawnData: the world's spawn (level.dat `spawn`). let old = self.level.world_spawn.replace(pos); self.level.world_spawn_angle = rot; - // A player whose respawn point is the world spawn (no bed, anchor or - // spawnpoint of its own) respawns at the new one. + // A player whose fallback is the world spawn (no spawnpoint of its + // own; a bed or an anchor that is gone falls back to it) respawns at + // the new one. let floor = |s: Vec3| [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32]; - if self.respawn_config.is_none() && self.spawn.map(floor) == old { + if self.spawn.map(floor) == old { self.spawn = Some(Vec3::new( f64::from(pos[0]) + 0.5, f64::from(pos[1]), diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 3de4341ad..752785084 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -291,12 +291,12 @@ impl Game<'_> { used = self.fixture_use_item(origin, op)?; } else if let Some(op) = case.get("respawn_at") { // ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at the origin. - let config = super::respawn_anchor::RespawnConfig { - dim: self.dim, - pos: [origin.x, origin.y, origin.z], - yaw: 0.0, - forced: op["forced"].as_bool().unwrap_or(false), - }; + let config = super::respawn_anchor::RespawnConfig::wrapped( + self.dim, + [origin.x, origin.y, origin.z], + op["yaw"].as_f64().map_or(0.0, |v| v as f32), + op["forced"].as_bool().unwrap_or(false), + ); let found = self.find_respawn_and_use(config, op["consume"].as_bool().unwrap_or(true))?; used.push(match found { diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index c3f34ebd3..d62c8ccc2 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -416,7 +416,15 @@ impl Game<'_> { f64::from(END_SPAWN[2]) + 0.5, )); } - // Leaving the End: the respawn position (the world spawn here). + // Leaving the End: the respawn position, a bed's found once it has + // loaded (findRespawnPositionAndUseSpawnBlock, not using it up). + if let Some(c) = self.respawn_config.filter(|c| c.dim == target) { + return Some(Vec3::new( + f64::from(c.pos[0]) + 0.5, + f64::from(c.pos[1]), + f64::from(c.pos[2]) + 0.5, + )); + } let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]); Some(Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5)) } @@ -487,7 +495,16 @@ impl Game<'_> { // Direction.WEST.toYRot(). return Ok((target, Some(90.0))); } - // ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column. + // ServerPlayer.findRespawnPositionAndUseSpawnBlock: where the bed or + // anchor puts the player, facing it; else onto the spawn column. + let mut target = target; + if let Some(c) = self.respawn_config.filter(|c| c.dim == self.dim) { + if let Some((at, yaw)) = self.find_respawn_and_use(c, false)? { + return Ok((at, Some(yaw))); + } + let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]); + target = Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5); + } let y = self .land_column(target.x.floor() as i32, target.z.floor() as i32) .map_or(target.y, f64::from); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 540f857d3..0527e30a0 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1507,11 +1507,22 @@ impl Game<'_> { // or another one's anchor or forced point, which its block resolves // once the level has loaded around it. let server = self.options.dedicated.is_some(); - let elsewhere = host.hub.guests[i] + let own = host.hub.guests[i] .respawn_elsewhere .as_ref() - .filter(|_| server) .map(RespawnConfig::from_saved); + let elsewhere = own.filter(|_| server); + // In the window's world a guest has no level of its own to wait in: + // its bed is resolved at once when its chunk is there, else it + // comes back on the bed. + let in_frame_bed = own.filter(|c| !server && c.dim == super::Dim::Overworld); + let spawn = in_frame_bed.map_or(spawn, |c| { + [ + f64::from(c.pos[0]) + 0.5, + f64::from(c.pos[1]) + 0.6, + f64::from(c.pos[2]) + 0.5, + ] + }); let level = elsewhere.map_or(super::Dim::Overworld, |c| c.dim); let spawn = elsewhere.map_or(spawn, |c| { [ @@ -1569,6 +1580,25 @@ impl Game<'_> { if let Some(config) = elsewhere { self.respawn_trip(conn, config); } + if let Some(c) = in_frame_bed + && self.dim == super::Dim::Overworld + && self.world.loaded(c.pos[0], c.pos[2]) + { + let found = self + .as_guest(host, conn, |g| g.resolve_server_respawn(c)) + .flatten(); + let world = self + .level + .world_spawn + .map_or([0.5, 80.0, 0.5], |[x, y, z]| { + [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5] + }); + let at = found.map_or(world, |(at, yaw)| { + host.hub.guests[i].yaw = yaw; + [at.x, at.y, at.z] + }); + host.hub.teleport(i, Some(at)); + } if away && let Err(e) = self.enter_level(Some(host), back) { log::error!("could not reopen {}: {e}", back.id()); } diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 9b6ecc203..392a53964 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -36,6 +36,15 @@ pub(super) struct RespawnConfig { pub(super) type SavedRespawn = (String, [i32; 3], f32, bool); impl RespawnConfig { + /// `RespawnData.of`: the yaw wrapped to [-180, 180). + pub(super) fn wrapped(dim: Dim, pos: [i32; 3], yaw: f32, forced: bool) -> Self { + Self { + dim, + pos, + yaw: wrap_degrees(f64::from(yaw)) as f32, + forced, + } + } pub(super) fn from_saved((dim, pos, yaw, forced): &SavedRespawn) -> Self { Self { dim: Dim::from_id(dim), @@ -80,7 +89,7 @@ pub(super) enum AnchorUse { } impl Game<'_> { - fn is_anchor(&self, state: BlockStateId) -> bool { + pub(super) fn is_anchor(&self, state: BlockStateId) -> bool { &*self.res.facts().get(state).name == "minecraft:respawn_anchor" } fn anchor_charges(&self, state: BlockStateId) -> i32 { @@ -456,9 +465,87 @@ impl Game<'_> { } None } + /// `AbstractBedBlock.findStandUpPosition` for a bed whose head is at + /// `pos`, facing `forward`, set from `yaw`: beside the bed on the side + /// the player faced away from, around it, then on it; a safe spot + /// first, else any spot (a bunk bed: around it, a block lower, then on + /// it). + pub(super) fn bed_stand_up(&self, pos: [i32; 3], forward: [i32; 3], yaw: f32) -> Option { + // Direction.getClockWise. + let right = [-forward[2], 0, forward[0]]; + // Direction.isFacingAngle. + let radians = yaw * 0.017_453_292; + let (dx, dz) = ( + -horizon_core::geometry::trig::sin(f64::from(radians)), + horizon_core::geometry::trig::cos(f64::from(radians)), + ); + let facing = right[0] as f32 * dx + right[2] as f32 * dz > 0.0; + let side = if facing { + [-right[0], 0, -right[2]] + } else { + right + }; + let (f, s) = ([forward[0], forward[2]], [side[0], side[2]]); + // bedSurroundStandUpOffsets and bedAboveStandUpOffsets. + let surround = [ + [s[0], s[1]], + [s[0] - f[0], s[1] - f[1]], + [s[0] - f[0] * 2, s[1] - f[1] * 2], + [-f[0] * 2, -f[1] * 2], + [-s[0] - f[0] * 2, -s[1] - f[1] * 2], + [-s[0] - f[0], -s[1] - f[1]], + [-s[0], -s[1]], + [-s[0] + f[0], -s[1] + f[1]], + [f[0], f[1]], + [s[0] + f[0], s[1] + f[1]], + ]; + let above = [[0, 0], [-f[0], -f[1]]]; + let at = |base: [i32; 3], offsets: &[[i32; 2]], check: bool| { + offsets.iter().find_map(|o| { + self.safe_dismount_location([base[0] + o[0], base[1], base[2] + o[1]], check) + }) + }; + let below = [pos[0], pos[1] - 1, pos[2]]; + // isBunkBed: a bed below. + if self.is_bed(self.world.block(below[0], below[1], below[2])) { + return at(pos, &surround, true) + .or_else(|| at(below, &surround, true)) + .or_else(|| at(pos, &above, true)) + .or_else(|| at(pos, &surround, false)) + .or_else(|| at(below, &surround, false)) + .or_else(|| at(pos, &above, false)); + } + let all: Vec<[i32; 2]> = surround.into_iter().chain(above).collect(); + at(pos, &all, true).or_else(|| at(pos, &all, false)) + } + pub(super) fn is_bed(&self, state: BlockStateId) -> bool { + self.res.facts().get(state).name.ends_with("_bed") + } + /// The bed's `facing`, as a step. + fn bed_forward(&self, state: BlockStateId) -> [i32; 3] { + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()); + match facing.as_deref() { + Some("south") => [0, 0, 1], + Some("west") => [-1, 0, 0], + Some("east") => [1, 0, 0], + _ => [0, 0, -1], + } + } + /// `BedRule.canSetSpawn` of the bed's rule attribute (`bed_rule`, + /// `straw_bed_rule`): only the Overworld's beds set the spawn, straw + /// beds never. + pub(super) fn bed_sets_spawn(&self, state: BlockStateId) -> bool { + self.dim == Dim::Overworld && &*self.res.facts().get(state).name != "minecraft:straw_bed" + } /// `ServerPlayer.findRespawnAndUseSpawnBlock` for a config in the loaded - /// dimension: the position and yaw, using an anchor's charge. A forced - /// point (`spawnpoint`) that is no anchor holds if a player fits in it. + /// dimension: the position and yaw, using an anchor's charge; a bed's + /// stand-up spot. A forced point (`spawnpoint`) that is no anchor or bed + /// holds if a player fits in it; anything else is gone. pub(super) fn find_respawn_and_use( &mut self, c: RespawnConfig, @@ -469,6 +556,12 @@ impl Game<'_> { && (c.forced || self.anchor_charges(state) > 0) && self.anchor_works()) { + // A bed where its bed rule lets it set the spawn. + if self.is_bed(state) && self.bed_sets_spawn(state) { + let facing = self.bed_forward(state); + let stand = self.bed_stand_up(c.pos, facing, c.yaw); + return Ok(stand.map(|p| (p, look_at_yaw(p, c.pos)))); + } let [x, y, z] = c.pos; let free = c.forced && !self.is_anchor(state) diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 1b1ec3a6d..1e94ec995 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -193,11 +193,16 @@ impl Game<'_> { _ => 1.0, }; self.end_portal_travel = end; - let scaled = self.end_destination(target).unwrap_or(Vec3::new( - from.x * scale, - from.y, - from.z * scale, - )); + // Leaving the End: the player's own respawn point. + let own = if end { + self.as_guest(host, conn, |g| g.end_destination(target)) + .flatten() + } else { + None + }; + let scaled = own + .or_else(|| self.end_destination(target)) + .unwrap_or(Vec3::new(from.x * scale, from.y, from.z * scale)); self.end_portal_travel = false; if let Err(e) = self.enter_level(Some(host), target) { log::error!("could not open {}: {e}", target.id()); @@ -244,13 +249,15 @@ impl Game<'_> { } /// `findRespawnAndUseSpawnBlock` for the player in place, at its point - /// in the level in place: where it stands up, facing the anchor, with - /// the deplete sound; else the point is forgotten + /// in the level in place: where it stands up, facing the anchor (with + /// the deplete sound) or the bed; else the point is forgotten /// (`block.minecraft.spawn.not_valid`). - fn resolve_server_respawn(&mut self, config: RespawnConfig) -> Option<(Vec3, f32)> { + pub(super) fn resolve_server_respawn(&mut self, config: RespawnConfig) -> Option<(Vec3, f32)> { + let [x, y, z] = config.pos; + let anchor = self.is_anchor(self.world.block(x, y, z)); match self.find_respawn_and_use(config, true) { Ok(Some((at, yaw))) => { - if !config.forced { + if !config.forced && anchor { let [x, y, z] = config.pos.map(f64::from); self.audio.play( "minecraft:block.respawn_anchor.deplete", @@ -357,7 +364,11 @@ impl Game<'_> { } } } else if trip.end { - match self.end_arrival(trip.target) { + let arrival = match self.as_guest(host, trip.conn, |g| g.end_arrival(trip.target)) { + Some(arrival) => arrival, + None => self.end_arrival(trip.target), + }; + match arrival { Ok((at, turned)) => (at, turned.unwrap_or(yaw)), Err(e) => { log::error!("End arrival: {e}"); diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 056f38e1c..dd86c8f9c 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2258,10 +2258,12 @@ pub struct Level { pub game_mode: i32, pub time: i64, pub day_time: i64, - /// The player's respawn point (bed, or the world spawn). + /// Where the player respawns when it has no bed or anchor: its forced + /// Overworld point (`spawnpoint`), or the world spawn. pub spawn: Option<[f64; 3]>, - /// A respawn point in another dimension than the Overworld (a respawn - /// anchor): dimension, block, yaw and `forced`. + /// A respawn point resolved through its block when the player respawns + /// (a bed, a respawn anchor, a forced point outside the Overworld): + /// dimension, block, yaw and `forced`. pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>, pub position: Option<[f64; 3]>, pub rotation: [f32; 2], @@ -2495,14 +2497,17 @@ impl Level { { let dimension = text(respawn.get("dimension")).unwrap_or_else(|| "minecraft:overworld".into()); - if dimension == "minecraft:overworld" { + let forced = number(respawn.get("forced")).is_some_and(|v| v != 0); + // A forced point in the Overworld (`spawnpoint`) is where the + // player respawns; anything else (a bed, an anchor) is resolved + // through its block then. + if dimension == "minecraft:overworld" && forced { self.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); } else { let yaw = match respawn.get("yaw") { Some(Tag::Float(b)) => f32::from_bits(*b), _ => 0.0, }; - let forced = number(respawn.get("forced")).is_some_and(|v| v != 0); self.respawn_elsewhere = Some((dimension, [pos[0], pos[1], pos[2]], yaw, forced)); } } @@ -2719,6 +2724,8 @@ impl Level { s[1].floor() as i32, s[2].floor() as i32, ]; + // A point of the player's own in the Overworld other than a bed + // (`respawn_elsewhere`): `spawnpoint`'s, forced. if Some(block) != self.world_spawn { entries.push(( "respawn", @@ -2727,6 +2734,7 @@ impl Level { ("pos", Tag::IntArray(block.to_vec())), ("yaw", Tag::Float(0f32.to_bits())), ("pitch", Tag::Float(0f32.to_bits())), + ("forced", Tag::Byte(1)), ]), )); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 43ec6d65a..a529ae6ac 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -655,7 +655,8 @@ public final class VanillaDispenserOracle { */ static List respawnAt(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject op) throws Exception { var config = new net.minecraft.server.level.ServerPlayer.RespawnConfig( - net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), pos, 0.0F, 0.0F), op.get("forced").getAsBoolean()); + net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), pos, + op.has("yaw") ? op.get("yaw").getAsFloat() : 0.0F, 0.0F), op.get("forced").getAsBoolean()); Method find = net.minecraft.server.level.ServerPlayer.class.getDeclaredMethod("findRespawnAndUseSpawnBlock", ServerLevel.class, net.minecraft.server.level.ServerPlayer.RespawnConfig.class, boolean.class); find.setAccessible(true); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 8a6cbbb4e..4d250b7a6 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -144,8 +144,11 @@ address. The script then checks, from both sides, what a guest's game used to ge than in the air on their own client as on the server, and it breaks (#1254). - worldspawn: the host moves the world spawn (`setworldspawn`): the host and the guest, with no bed, respawn there (#1310). -- shield: the host axes the guest's raised shield, then the guest the host's: it stays disabled - for 5 s on that player's own cooldown, then blocks again (#1316). +- shield: a vindicator's axe disables the host's, then the guest's, raised shield: the server + counts its 5 s cooldown down once a tick (#1316). +- beds: the host and the guest each set their respawn point at a bed and die elsewhere: they + stand up beside the bed, or, when the bed is gone or boxed in by stone, come back at + the world spawn (#1308). - deathmining: the host and the guest each die while breaking obsidian and let go on the death screen: once respawned, the obsidian stays (#1315). - contacts: the host and the guest each stand on magma (and sneak on it), stand on a lit campfire, @@ -198,7 +201,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', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +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', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2842,6 +2845,60 @@ def check_world_spawn(host, guest, out): return seen +def check_beds(host, guest, out): + """A bed sets the respawn point (day or night): respawning stands the player up beside it; a bed + that is gone, or boxed in by stone so there is nowhere to stand up, sends the player to the world + spawn instead (#1308). The host, then the guest, each for the three beds.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command='gamerule respawn_radius 0') + host('command', command=f'setworldspawn {hx} {hy} {hz}') + host('command', command='time set 1000') + seen = {} + try: + for game, dz in ((host, -6), (guest, 6)): + game('command', command='gamemode survival') + x, y, z = hx + 12, hy, hz + dz + for case in ('intact', 'gone', 'boxed'): + game('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 4} {y - 1} {z + 3} minecraft:stone') + game('command', command=f'fill {x - 3} {y} {z - 3} {x + 4} {y + 3} {z + 3} minecraft:air') + 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]') + game('command', command=f'tp @s {x + 0.5} {y} {z + 1.5}') + game.wait(20) + game.raw('interact', x + 1, y, z) + game.wait(10) + # Die elsewhere, by the world spawn. + game('command', command=f'tp @s {hx + 0.5} {hy} {hz + 3.5}') + game.wait(10) + if case == 'gone': + game('command', command=f'fill {x} {y} {z} {x + 1} {y} {z} minecraft:air') + elif case == 'boxed': + game('command', command=f'fill {x - 2} {y} {z - 2} {x + 3} {y + 2} {z + 2} minecraft:stone replace minecraft:air') + game.wait(5) + game('command', command='kill @s') + game.wait(20) + respawn_when_ready(game) + game.wait(60) + at = [round(v, 2) for v in pos_of(game)] + seen[f'{game.name}-{case}'] = {'at': at, 'bed': [x + 1, y, z], 'health': own(game)['health']} + game.shot(out, f'beds-{case}') + finally: + host('command', command='gamerule respawn_radius 10') + host('command', command='time set 1000') + for game in (host, guest): + game('command', command=f'tp @s {hx + 0.5} {hy} {hz + 0.5}') + guest.wait(20) + for case, s in seen.items(): + (px, py, pz), (bx, by, bz) = s['at'], s['bed'] + if case.endswith('intact'): + near = ((px - bx - 0.5) ** 2 + (pz - bz - 0.5) ** 2) ** 0.5 + assert near < 2.6 and abs(py - by) < 0.6, f'{case}: not beside its bed: {seen}' + else: + assert abs(px - (hx + 0.5)) < 1 and abs(pz - (hz + 0.5)) < 1, f'{case}: not at the world spawn: {seen}' + assert s['health'] > 0, f'{case}: died again after respawning: {seen}' + return seen + + def check_death_mining(host, guest, out): """A player who dies while breaking obsidian, and lets go of attack on the death screen, doesn't break it once respawned: death forgets the digging (#1315).""" @@ -3759,7 +3816,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, - 'worldspawn': check_world_spawn, 'shield': check_shield, 'deathmining': check_death_mining, + 'worldspawn': check_world_spawn, 'beds': check_beds, 'shield': check_shield, 'deathmining': check_death_mining, 'contacts': check_contacts, 'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava, 'levels': check_levels, 'drops': check_drops, 'underwater': check_underwater} diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index 398f55a92..d6e5f899f 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -23,7 +23,9 @@ explode elsewhere (`RespawnAnchorBlock`, through the stand-in level's real `ServerExplosion`, with water at the anchor). Respawn cases call `ServerPlayer.findRespawnAndUseSpawnBlock` on an anchor among blocks (`RespawnAnchorBlock.findStandUpPosition` through `DismountHelper`): the -position, the yaw that faces the anchor and the charge it uses. Beds and straw +position, the yaw that faces the anchor and the charge it uses; others on a +bed's head set from some yaw (`AbstractBedBlock.findStandUpPosition`: intact, +bunk, only the foot left or gone, crowded around and on top). Beds and straw beds clicked (head or foot, whole or broken) in the Nether and the End blow up or fall apart (`AbstractBedBlock.useWithoutItem` under the dimension's `bed_rule`: `BedBlock.destroyOnUse`, `StrawBedBlock.destroyBed`). Horizon runs @@ -90,6 +92,52 @@ BED_COLORS = ['red', 'white', 'black', 'cyan', 'lime'] FACINGS = {'north': (0, -1), 'south': (0, 1), 'west': (-1, 0), 'east': (1, 0)} +def bed_respawn_case(rng, states, case): + """Respawning at a bed's head set from some yaw: intact, a bunk bed, only the foot left or + gone, with blocks around and on it, in the Overworld (and a few in the Nether or the End).""" + name = 'straw_bed' if rng.random() < 0.15 else rng.choice(BED_COLORS) + '_bed' + facing = rng.choice(list(FACINGS)) + fx, fz = FACINGS[facing] + bed = {} + kept = rng.random() + if kept < 0.75: + bed[(0, 0, 0)] = states.get(name, facing=facing, part='head', occupied='false') + elif kept < 0.85: + bed[(0, 0, 0)] = states.get(rng.choice(['stone', 'white_carpet', 'oak_slab'])) + if kept < 0.9 or rng.random() < 0.5: + bed[(-fx, 0, -fz)] = states.get(name, facing=facing, part='foot', occupied='false') + if rng.random() < 0.2: + # A bunk bed: another bed below. + bed[(0, -1, 0)] = states.get(name, facing=facing, part='head', occupied='false') + bed[(-fx, -1, -fz)] = states.get(name, facing=facing, part='foot', occupied='false') + crowd = rng.choice([0.0, 0.1, 0.3, 0.6, 0.95]) + cells = [[*k, v] for k, v in bed.items()] + if (0, 0, 0) not in bed: + cells.insert(0, [0, 0, 0, states.get('air')]) + for dy in (-2, -1, 0, 1, 2): + for dx in range(-3, 4): + for dz in range(-3, 4): + if (dx, dy, dz) in bed or (dx, dy, dz) == (0, 0, 0): + continue + if dy == -1 and (dx, 0, dz) in bed: + name2 = 'stone' + elif dy < 0: + name2 = rng.choice(['stone'] * 8 + STAND) + elif rng.random() < crowd: + name2 = rng.choice(['stone'] * 4 + STAND) + else: + continue + if name2 == 'air': + continue + state = states.any(rng, name2) if name2 in ('oak_trapdoor', 'oak_slab', 'snow', 'campfire', 'water', 'ladder') else states.get(name2) + cells.append([dx, dy, dz, state]) + if rng.random() < 0.1: + case['dim'] = rng.choice(['nether', 'end']) + yaw = rng.choice([0.0, 90.0, -90.0, 180.0, round(rng.uniform(-720, 720), rng.choice([0, 2]))]) + case['respawn_at'] = {'forced': rng.random() < 0.15, 'consume': rng.random() < 0.8, 'yaw': yaw} + case['cells'] = cells + + def bed_case(rng, states, case): """A bed (or straw bed) clicked in the Nether or the End, among blocks.""" name = 'straw_bed' if rng.random() < 0.25 else rng.choice(BED_COLORS) + '_bed' @@ -224,6 +272,12 @@ def cases(facts, count, seed): case['mode'] = 'dispense' yield case continue + if rng.random() < 0.1: + bed_respawn_case(rng, states, case) + case['items'] = [] + case['mode'] = 'dispense' + yield case + continue if rng.random() < 0.15: anchor_case(rng, states, case) case['items'] = []