diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..71610bfb7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -88,6 +88,7 @@ mod recipe_book; mod remote; mod render_control; mod render_tick; +mod respawn_anchor; mod scoreboard; mod screens; mod sculk; @@ -791,6 +792,11 @@ struct Game<'a> { portals: nether_portal::Portals, /// The pending travel goes through an End portal (EndPortalBlock destinations). end_travel: bool, + /// The respawn point when it is not the world spawn or a bed: a respawn + /// anchor (`game/respawn_anchor.rs`). + respawn_config: Option, + /// A respawn travelling to its anchor's dimension and chunks. + respawn_travel: Option, /// The next enter_dimension call comes from an End portal. end_portal_travel: bool, end: end::EndState, @@ -1725,7 +1731,10 @@ impl Game<'_> { food.saturation = (food.saturation + 0.4).min(food.food as f32); } } - PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {} + PlayerEffect::RespawnAnchor => { + self.respawn_anchor_used([pos.x, pos.y, pos.z])? + } + PlayerEffect::InteractLoot(_) => {} }, LevelEvent::PrimeTnt { pos, rot } => self.add_primed_tnt(pos, rot, 80), LevelEvent::BlockEvent { @@ -2119,6 +2128,7 @@ impl Game<'_> { return Ok(()); } let sneaking = self.keys.contains(&KeyCode::ShiftLeft); + let mut anchor_passed = None; // MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item. if !(sneaking && self.held().is_some()) && let Some(hit) = self.pick() @@ -2136,6 +2146,15 @@ impl Game<'_> { self.swing_arm(); return Ok(()); } + match self.use_respawn_anchor(hit.pos, held.as_ref())? { + respawn_anchor::AnchorUse::Charged => { + self.swing_arm(); + return Ok(()); + } + // The main hand passes; its item is used, then the off hand's glowstone. + respawn_anchor::AnchorUse::Pass => anchor_passed = Some(hit.pos), + respawn_anchor::AnchorUse::Other => {} + } let face = match hit.face { [0, 1, 0] => Direction::Up, [0, -1, 0] => Direction::Down, @@ -2157,17 +2176,21 @@ impl Game<'_> { }; let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); let item = held.as_ref().map(|s| s.item.to_string()); - let result = self.with_level(|b, level, ticks| { - b.use_item_on( - level, - ticks, - BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), - face, - at, - player, - item.as_deref(), - ) - }); + let result = if anchor_passed.is_some() { + horizon_world::level::InteractionResult::Pass + } else { + self.with_level(|b, level, ticks| { + b.use_item_on( + level, + ticks, + BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + face, + at, + player, + item.as_deref(), + ) + }) + }; self.process_level_events()?; if result.consumes_action() { self.swing_arm(); @@ -2175,6 +2198,12 @@ impl Game<'_> { } } let Some(stack) = self.held().cloned() else { + // Minecraft.startUseItem goes on to the off hand. + if let Some(pos) = anchor_passed + && self.charge_anchor_from_offhand(pos)? + { + return Ok(()); + } self.use_offhand(); return Ok(()); }; @@ -2239,6 +2268,11 @@ impl Game<'_> { return Ok(()); }; if info.block.is_none() { + if let Some(pos) = anchor_passed + && self.charge_anchor_from_offhand(pos)? + { + return Ok(()); + } self.use_offhand(); return Ok(()); } @@ -2585,7 +2619,10 @@ impl Game<'_> { self.streaming.center = (cx, cz); if (-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { let (player, target) = self.travelling.take().ok_or("travel")?; - if self.end_travel { + if let Some(config) = self.respawn_travel.take() { + drop(player); + self.place_respawned(config)?; + } else if self.end_travel { self.place_after_end_travel(player, target)?; } else { self.place_after_travel(player, target)?; @@ -5649,6 +5686,17 @@ impl Game<'_> { self.travelling = None; self.player = None; self.spawn = None; + self.respawn_travel = None; + self.respawn_config = + self.level + .respawn_elsewhere + .as_ref() + .map(|(dim, pos, yaw, forced)| respawn_anchor::RespawnConfig { + dim: Dim::from_id(dim), + pos: *pos, + yaw: *yaw, + forced: *forced, + }); self.spawn_search = 0; self.spawn_origin = None; self.spawn_spiral = Default::default(); @@ -7097,6 +7145,8 @@ impl Game<'_> { 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, @@ -7474,6 +7524,9 @@ impl Game<'_> { level.weather = self.world.weather; level.day_time = self.world.day_time; level.spawn = self.spawn.map(|s| [s.x, s.y, s.z]); + level.respawn_elsewhere = self + .respawn_config + .map(|c| (c.dim.id().to_owned(), c.pos, c.yaw, c.forced)); level.rotation = [self.yaw, self.pitch]; level.xp_level = self.experience.level; level.xp_progress = self.experience.progress; @@ -9050,6 +9103,8 @@ pub fn run() -> Result<()> { travelling: None, portals: Default::default(), end_travel: false, + respawn_config: None, + respawn_travel: None, end_portal_travel: false, end: Default::default(), block_ticks: Ticks::new(0), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index aff5ad2a1..15d43c80b 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2010,6 +2010,7 @@ impl Game<'_> { f64::from(pos[1]), f64::from(pos[2]) + 0.5, )); + self.respawn_config = None; let dim = Text::literal(self.dim.id()); let p = pos.map(|v| Text::literal(v.to_string())); let mut args = vec![ diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index ab6a79961..6e10b53b1 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -137,6 +137,8 @@ impl Game<'_> { // Hopper cooldowns of an earlier case. self.hoppers.clear(); self.ui.rules = Default::default(); + self.dim = super::Dim::Overworld; + self.respawn_config = None; // The oracle level plays on normal difficulty. self.ui.difficulty = 2; // The oracle level has world seed 0 and fresh random sequences. @@ -162,6 +164,9 @@ impl Game<'_> { } } self.world.game_time = case["time"].as_i64().unwrap_or(0); + if case["dim"].as_str() == Some("nether") { + self.dim = super::Dim::Nether; + } // The oracle level's clock stands at day time 6000. self.world.day_time = 6000; if let Some(rules) = case["rules"].as_object() { @@ -272,6 +277,26 @@ impl Game<'_> { used = self.fixture_use(origin, op)?; } else if let Some(op) = case.get("use_item") { 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 found = + self.find_respawn_and_use(config, op["consume"].as_bool().unwrap_or(true))?; + used.push(match found { + Some((p, yaw)) => format!( + "respawn {} {} {} {}", + num(p.x), + num(p.y), + num(p.z), + yaw.to_bits() as i32 + ), + None => "respawn none".to_owned(), + }); } else if case.get("hopper").is_some() { // HopperBlockEntity.pushItemsTick, once. self.hopper_try_move_items((origin.x, origin.y, origin.z)); @@ -447,14 +472,24 @@ impl Game<'_> { GameMode::Survival }; self.creative = self.mode == GameMode::Creative; + let distance = op["distance"].as_f64().unwrap_or(3.0); let mut player = PlayerMotion::new( self.motion, horizon_core::geometry::Vec3::new( f64::from(pos.x) + 0.5, f64::from(pos.y) + 1.0, - f64::from(pos.z) + 3.5, + f64::from(pos.z) + 0.5 + distance, ), )?; + if let Some(r) = op["respawn"].as_array() { + let p = |i: usize| r.get(i).and_then(Value::as_i64).unwrap_or(0) as i32; + self.respawn_config = Some(super::respawn_anchor::RespawnConfig { + dim: self.dim, + pos: [p(0), p(1), p(2)], + yaw: 0.0, + forced: false, + }); + } player.health.food.food = op["food"].as_i64().unwrap_or(20) as i32; self.player = Some(player); self.yaw = 0.0; @@ -488,7 +523,10 @@ impl Game<'_> { let key = m.component()["translate"] .as_str() .map_or_else(|| m.plain(), str::to_owned); - out.push(format!("msg {key}")); + // The oracle player's advancements are not tracked. + if !key.starts_with("chat.type.advancement") { + out.push(format!("msg {key}")); + } } if let Some(s) = &stack { let used = self.stats.get("used", &s.item) - used_before; @@ -504,6 +542,16 @@ impl Game<'_> { "held {} using {using}", canon_stack(self.inventory[self.selected].as_ref()) )); + out.push(match self.respawn_config { + Some(c) => format!( + "respawn {} {},{},{}", + c.dim.id(), + c.pos[0], + c.pos[1], + c.pos[2] + ), + None => "respawn -".to_owned(), + }); self.player = None; self.using = None; Ok(out) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index e6be63093..126bd322b 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -494,14 +494,16 @@ impl Game<'_> { Ok(()) } - /// Dying in the End respawns in the Overworld. + /// Dying away from the Overworld respawns at the world spawn there. pub(super) fn respawn_out_of_end(&mut self) -> Result<()> { - if self.dim != Dim::End || self.player.is_none() { + if self.dim == Dim::Overworld || self.player.is_none() { return Ok(()); } self.end_portal_travel = true; let result = self.enter_dimension(Dim::Overworld); self.end_portal_travel = false; + // The arrival places a fresh player at the spawn. + self.end_travel = true; result } diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 1332ad51d..c03b99609 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -109,8 +109,14 @@ impl Game<'_> { } hits as f32 / count as f32 } - /// `ServerExplosion.calculateExplodedPositions`. - fn exploded_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> { + /// `ServerExplosion.calculateExplodedPositions`; `resists` overrides one + /// block's resistance (`ExplosionDamageCalculator.getBlockExplosionResistance`). + fn exploded_positions( + &mut self, + center: [f64; 3], + radius: f32, + resists: Option<([i32; 3], f32)>, + ) -> Vec<[i32; 3]> { let (min_y, max_y) = self.with_level(|_, level, _| { use horizon_world::level::LevelAccess; (level.min_y(), level.max_y()) @@ -147,8 +153,14 @@ impl Game<'_> { } else { 0.0 }; - if !self.res.facts.is_air(state) || f.fluid != Fluid::None { - power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; + match resists { + Some((at, resistance)) if at == pos => { + power -= (resistance + 0.3) * 0.3; + } + _ if !self.res.facts.is_air(state) || f.fluid != Fluid::None => { + power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; + } + _ => {} } if power > 0.0 { set.put(Key(pos), ()); @@ -163,8 +175,9 @@ impl Game<'_> { } set.entries().map(|(k, _)| k.0).collect() } - /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT). - fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32) { + /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT); + /// the player takes `damage_type`. + fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) { if radius < 1.0e-5 { return; } @@ -223,7 +236,7 @@ impl Game<'_> { let mut hurt = false; let creative = self.creative; if let Some(p) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id("minecraft:explosion") + && let Some(id) = self.motion.health.damage.id(damage_type) { // Creative players are invulnerable to explosions. if !creative && player_hurtable { @@ -334,6 +347,26 @@ impl Game<'_> { radius: f32, interaction: BlockInteraction, fire: bool, + ) -> Result<()> { + self.server_explode_as( + center, + radius, + interaction, + fire, + "minecraft:explosion", + None, + ) + } + /// `server_explode` with the damage type the player takes and a block + /// whose explosion resistance the damage calculator overrides. + pub(super) fn server_explode_as( + &mut self, + center: [f64; 3], + radius: f32, + interaction: BlockInteraction, + fire: bool, + damage_type: &str, + resists: Option<([i32; 3], f32)>, ) -> Result<()> { if let Some(p) = &self.player { let d = [ @@ -344,11 +377,11 @@ impl Game<'_> { let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius }); } - let mut targets = self.exploded_positions(center, radius); // Explosion.explode: the blast is heard. let ctx = horizon_client::sculk::Context::default(); self.post_game_event("minecraft:explode", center, ctx); - self.explosion_hurt_entities(center, radius); + let mut targets = self.exploded_positions(center, radius, resists); + self.explosion_hurt_entities(center, radius, damage_type); if interaction != BlockInteraction::Keep { // Util.shuffle(list, level.random) for i in (2..=targets.len()).rev() { @@ -375,8 +408,12 @@ impl Game<'_> { .facts .get(self.world.block(pos[0], pos[1] - 1, pos[2])) .solid_render - && let Some(fire) = self.res.assets.registry.default_state("minecraft:fire") { + // BaseFireBlock.getState: soul fire on its base blocks, + // fire shaped by its neighbours elsewhere. + let at = BlockPos::new(pos[0], pos[1], pos[2]); + let fire = + self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at)); self.level_set(pos, fire)?; } } @@ -420,32 +457,36 @@ impl Game<'_> { } if !is_tnt { let dynamic = self.pending.dynamic(pos); - let drops = self.res.items.block_drops_full( + // LootContextParams.EXPLOSION_RADIUS under DESTROY_WITH_DECAY: the + // tables' survives_explosion and explosion_decay draw from their + // random sequence. + let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius); + let drops = self.res.items.block_drops_exploded( self.res.assets.registry, state, None, &dynamic, &mut self.world.random, Some((&mut self.rand_sequences, self.level.seed)), + decay, ); for mut stack in drops { if &*stack.item == "minecraft:air" || stack.count == 0 { continue; } self.pending.attach(pos, &mut stack); - // survives_explosion / explosion_decay: 1 / radius per stack. - if interaction == BlockInteraction::DestroyWithDecay - && self.world.random.next_float() > 1.0 / radius - { - continue; - } add_or_append_stack(stacks, stack, pos); } } self.pending.clear(pos); self.level_set(pos, self.world.air)?; - if is_tnt { - self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true); + // TntBlock.wasExploded: new PrimedTnt (its push drawn first), then + // getRandomShortFuse(80); no game event. + if is_tnt && self.ui.rules.bool("tnt_explodes") { + let r = &mut self.world.random; + let rot = r.next_double() * f64::from(std::f32::consts::TAU); + let fuse = r.next_int_bound(20).unwrap_or(0) + 10; + self.add_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), rot, fuse); } Ok(()) } diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs new file mode 100644 index 000000000..b1b9e18fe --- /dev/null +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -0,0 +1,542 @@ +//! `RespawnAnchorBlock` in the game: glowstone charges it (`useItemOn`), a +//! right click on a charged anchor sets the respawn point in the Nether and +//! blows it up anywhere else (`useWithoutItem`), and respawning goes to it +//! (`ServerPlayer.findRespawnAndUseSpawnBlock`, `PlayerList.respawn`), +//! using a charge. +use super::{Dim, Game}; +use horizon_client::{ + Result, + blocks::Fluid, + collisions::{SceneCollisions, no_collision_empty}, + items::ItemStack, + mobs::Who, + motion::PlayerMotion, + text::Text, +}; +use horizon_core::{ + geometry::{Aabb, Axis, Vec3, VoxelShape}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::{collision_context::CollisionContext, registry::BlockStateId}; + +/// `ServerPlayer.RespawnConfig`: a respawn point other than the world spawn +/// that the game resolves through its block (a respawn anchor). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct RespawnConfig { + pub dim: Dim, + pub pos: [i32; 3], + pub yaw: f32, + pub forced: bool, +} + +/// `RespawnAnchorBlock.RESPAWN_HORIZONTAL_OFFSETS`, then the same a block +/// below, a block above, and straight above. +const HORIZONTAL: [[i32; 3]; 8] = [ + [0, 0, -1], + [-1, 0, 0], + [0, 0, 1], + [1, 0, 0], + [-1, 0, -1], + [1, 0, -1], + [-1, 0, 1], + [1, 0, 1], +]; +fn respawn_offsets() -> impl Iterator { + HORIZONTAL + .into_iter() + .chain(HORIZONTAL.into_iter().map(|[x, y, z]| [x, y - 1, z])) + .chain(HORIZONTAL.into_iter().map(|[x, y, z]| [x, y + 1, z])) + .chain(std::iter::once([0, 1, 0])) +} + +/// What a right click with an item does to an anchor before `useWithoutItem`. +pub(super) enum AnchorUse { + /// Glowstone charged it. + Charged, + /// `PASS`: the off hand's glowstone charges it instead. + Pass, + /// `TRY_WITH_EMPTY_HAND`, or not an anchor. + Other, +} + +impl Game<'_> { + fn is_anchor(&self, state: BlockStateId) -> bool { + &*self.res.facts.get(state).name == "minecraft:respawn_anchor" + } + fn anchor_charges(&self, state: BlockStateId) -> i32 { + self.res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("charges")) + .and_then(|c| c.parse().ok()) + .unwrap_or(0) + } + fn anchor_with_charges(&self, state: BlockStateId, charges: i32) -> Option { + let mut s = self.res.assets.registry.state(state)?.clone(); + s.properties.insert("charges".into(), charges.to_string()); + self.res.assets.registry.resolve(&s).ok() + } + /// `RespawnAnchorBlock.canSetSpawn`: the `respawn_anchor_works` attribute + /// (only the Nether's dimension type sets it). + pub(super) fn anchor_works(&self) -> bool { + self.dim == Dim::Nether + } + /// `RespawnAnchorBlock.charge`: one more charge, the block change and the sound. + fn charge_anchor( + &mut self, + pos: [i32; 3], + state: BlockStateId, + who: Option, + ) -> Result<()> { + let Some(next) = self.anchor_with_charges(state, self.anchor_charges(state) + 1) else { + return Ok(()); + }; + self.level_set(pos, next)?; + self.post_block_game_event("minecraft:block_change", pos, who, Some(next)); + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio + .play("minecraft:block.respawn_anchor.charge", Some(at), 1.0, 1.0); + Ok(()) + } + /// `RespawnAnchorBlock.useItemOn` with `held` in the main hand. + pub(super) fn use_respawn_anchor( + &mut self, + pos: [i32; 3], + held: Option<&ItemStack>, + ) -> Result { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !self.is_anchor(state) { + return Ok(AnchorUse::Other); + } + let fuel = |s: Option<&ItemStack>| s.is_some_and(|s| &*s.item == "minecraft:glowstone"); + let chargeable = self.anchor_charges(state) < 4; + if fuel(held) && chargeable { + let used = held.cloned(); + self.charge_anchor(pos, state, Some(Who::Player))?; + // itemStack.consume(1, player); the criterion sees the stack as used. + self.consume_held(); + if let Some(stack) = used { + self.trigger_block("minecraft:item_used_on_block", pos, &stack); + } + return Ok(AnchorUse::Charged); + } + if fuel(self.offhand.as_ref()) && chargeable { + return Ok(AnchorUse::Pass); + } + Ok(AnchorUse::Other) + } + /// The off hand's glowstone on an anchor the main hand passed on. + pub(super) fn charge_anchor_from_offhand(&mut self, pos: [i32; 3]) -> Result { + let state = self.world.block(pos[0], pos[1], pos[2]); + let fuel = self + .offhand + .as_ref() + .is_some_and(|s| &*s.item == "minecraft:glowstone"); + if !self.is_anchor(state) || !fuel || self.anchor_charges(state) >= 4 { + return Ok(false); + } + let used = self.offhand.clone(); + self.charge_anchor(pos, state, Some(Who::Player))?; + if !self.creative + && let Some(s) = self.offhand.as_mut() + { + s.count -= 1; + if s.count == 0 { + self.offhand = None; + } + } + if let Some(stack) = used { + self.trigger_block("minecraft:item_used_on_block", pos, &stack); + } + self.swing_arm(); + Ok(true) + } + /// `RespawnAnchorBlock.useWithoutItem` on a charged anchor: outside the + /// Nether it explodes; inside, it becomes the respawn point. + pub(super) fn respawn_anchor_used(&mut self, pos: [i32; 3]) -> Result<()> { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !self.anchor_works() { + return self.explode_anchor(pos, state); + } + let config = RespawnConfig { + dim: self.dim, + pos, + yaw: 0.0, + forced: false, + }; + // RespawnConfig.isSamePosition: dimension and block. + let same = self + .respawn_config + .is_some_and(|c| c.dim == config.dim && c.pos == config.pos); + if !same { + // setRespawnPosition(config, true): the message, the point; the + // anchor replaces a bed. + self.system_message(Text::translate("block.minecraft.set_spawn", &[])); + self.respawn_config = Some(config); + if let Some([x, y, z]) = self.level.world_spawn { + self.spawn = Some(Vec3::new( + f64::from(x) + 0.5, + f64::from(y), + f64::from(z) + 0.5, + )); + } + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play( + "minecraft:block.respawn_anchor.set_spawn", + Some(at), + 1.0, + 1.0, + ); + } + Ok(()) + } + /// `RespawnAnchorBlock.isWaterThatWouldFlow`. + fn water_would_flow(&self, p: [i32; 3]) -> bool { + let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + if f.fluid != Fluid::Water { + return false; + } + if f.fluid_level == 8 && !f.fluid_falling { + return true; + } + if f.fluid_level < 2 { + return false; + } + self.res + .facts + .get(self.world.block(p[0], p[1] - 1, p[2])) + .fluid + != Fluid::Water + } + /// `RespawnAnchorBlock.explode`: the anchor goes, then a power 5 fiery + /// explosion (`badRespawnPointExplosion`, `ExplosionInteraction.BLOCK`) + /// whose centre resists like water when water would flow into it. + fn explode_anchor(&mut self, pos: [i32; 3], _state: BlockStateId) -> Result<()> { + self.level_set(pos, self.world.air)?; + let horizontal = [[0, 0, -1], [0, 0, 1], [-1, 0, 0], [1, 0, 0]] + .into_iter() + .any(|d| self.water_would_flow([pos[0] + d[0], pos[1], pos[2] + d[2]])); + let above = self + .res + .facts + .get(self.world.block(pos[0], pos[1] + 1, pos[2])) + .fluid + == Fluid::Water; + let in_water = horizontal || above; + let center = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.block_explosion(center, in_water.then_some(pos)) + } + /// `Level.explode(null, badRespawnPointExplosion(center), calculator, + /// center, 5, true, ExplosionInteraction.BLOCK)` (beds and anchors): + /// `water_at` is the block that resists like water. + pub(super) fn block_explosion( + &mut self, + center: [f64; 3], + water_at: Option<[i32; 3]>, + ) -> Result<()> { + let interaction = if self.ui.rules.bool("block_explosion_drop_decay") { + super::explosion::BlockInteraction::DestroyWithDecay + } else { + super::explosion::BlockInteraction::Destroy + }; + self.server_explode_as( + center, + 5.0, + interaction, + true, + "minecraft:bad_respawn_point", + water_at.map(|p| (p, 100.0)), + ) + } + + // ---- respawning ------------------------------------------------------- + + /// `DismountHelper.nonClimbableShape`: the collision shape, empty for + /// climbable blocks and open trapdoors. + fn non_climbable_shape(&self, p: [i32; 3]) -> VoxelShape { + let state = self.world.block(p[0], p[1], p[2]); + let name = &self.res.facts.get(state).name; + let open_trapdoor = name.ends_with("_trapdoor") + && self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("open")) + .is_some_and(|v| v == "true"); + if self.block_in_tag("minecraft:climbable", name) || open_trapdoor { + return VoxelShape::empty(); + } + let binding = self.collision; + let mut scene = SceneCollisions { + world: &self.world, + binding, + subject: None, + }; + binding + .collision_shape_with_context( + &mut scene, + state, + BlockPos::new(p[0], p[1], p[2]), + &CollisionContext::empty(false), + ) + .unwrap_or_else(|_| VoxelShape::empty()) + } + fn block_in_tag(&self, tag: &str, block: &str) -> bool { + self.res + .items + .block_tags + .get(tag) + .is_some_and(|s| s.contains(block)) + } + /// `EntityType.isBlockDangerous` for the player. + fn dangerous_for_player(&self, p: [i32; 3]) -> bool { + let state = self.world.block(p[0], p[1], p[2]); + let name = &*self.res.facts.get(state).name; + let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire") + && self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("lit")) + .is_some_and(|v| v == "true"); + // NodeEvaluator.isBurningBlock, then the hurting plants and snow. + self.block_in_tag("minecraft:fire", name) + || matches!( + name, + "minecraft:lava" + | "minecraft:magma_block" + | "minecraft:lava_cauldron" + | "minecraft:wither_rose" + | "minecraft:sweet_berry_bush" + | "minecraft:cactus" + | "minecraft:powder_snow" + ) + || lit_campfire + } + /// `DismountHelper.findSafeDismountLocation` for a standing player. + fn safe_dismount_location(&self, p: [i32; 3], check_dangerous: bool) -> Option { + if check_dangerous && self.dangerous_for_player(p) { + return None; + } + let shape = self.non_climbable_shape(p); + let below = self.non_climbable_shape([p[0], p[1] - 1, p[2]]); + let floor = horizon_core::geometry::block_floor_height(&shape, || &below); + // DismountHelper.isBlockFloorValid. + if floor.is_infinite() || floor >= 1.0 { + return None; + } + if check_dangerous && floor <= 0.0 && self.dangerous_for_player([p[0], p[1] - 1, p[2]]) { + return None; + } + let position = Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + floor, + f64::from(p[2]) + 0.5, + ); + // EntityDimensions.makeBoundingBox for 0.6 by 1.8 (the half width is a float). + let half = f64::from(0.6f32 / 2.0); + let bounds = Aabb::new( + Vec3::new(position.x - half, position.y, position.z - half), + Vec3::new( + position.x + half, + position.y + f64::from(1.8f32), + position.z + half, + ), + ); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + if !no_collision_empty(&mut scene, bounds) { + return None; + } + let name = |q: [i32; 3]| { + self.res + .facts + .get(self.world.block(q[0], q[1], q[2])) + .name + .clone() + }; + if self.block_in_tag("minecraft:invalid_spawn_inside", &name(p)) + || self.block_in_tag( + "minecraft:invalid_spawn_inside", + &name([p[0], p[1] + 1, p[2]]), + ) + { + return None; + } + // WorldBorder.isWithinBounds(box). + let (lo, hi) = (bounds.min(Axis::X), bounds.max(Axis::X) - 1.0e-5); + let (lz, hz) = (bounds.min(Axis::Z), bounds.max(Axis::Z) - 1.0e-5); + (self.border.contains(lo, lz) && self.border.contains(hi, hz)).then_some(position) + } + /// `RespawnAnchorBlock.findStandUpPosition`: a safe spot around the + /// anchor, else any spot. + pub(super) fn anchor_stand_up(&self, pos: [i32; 3]) -> Option { + for check in [true, false] { + for d in respawn_offsets() { + let p = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + if let Some(at) = self.safe_dismount_location(p, check) { + return Some(at); + } + } + } + None + } + /// `ServerPlayer.findRespawnAndUseSpawnBlock` for an anchor config in the + /// loaded dimension: the position and yaw, using a charge. + pub(super) fn find_respawn_and_use( + &mut self, + c: RespawnConfig, + consume: bool, + ) -> Result> { + let state = self.world.block(c.pos[0], c.pos[1], c.pos[2]); + if !(self.is_anchor(state) + && (c.forced || self.anchor_charges(state) > 0) + && self.anchor_works()) + { + return Ok(None); + } + let stand = self.anchor_stand_up(c.pos); + if !c.forced + && consume + && stand.is_some() + && let Some(next) = self.anchor_with_charges(state, self.anchor_charges(state) - 1) + { + self.level_set(c.pos, next)?; + } + Ok(stand.map(|p| (p, look_at_yaw(p, c.pos)))) + } + /// The death screen's respawn with an anchor as the respawn point: travel + /// to its dimension and wait for its chunks (`travelling`), then resolve + /// it in [`Game::place_respawned`]. + pub(super) fn begin_anchor_respawn(&mut self) -> Result { + let Some(config) = self.respawn_config else { + return Ok(false); + }; + if self.player.is_none() { + return Ok(false); + } + if self.dim != config.dim { + self.end_portal_travel = false; + self.enter_dimension(config.dim)?; + } else { + let player = self.player.take().ok_or("player")?; + self.travelling = Some((player, Vec3::ZERO)); + } + let target = Vec3::new( + f64::from(config.pos[0]) + 0.5, + f64::from(config.pos[1]), + f64::from(config.pos[2]) + 0.5, + ); + if let Some((_, t)) = self.travelling.as_mut() { + *t = target; + } + self.end_travel = false; + self.respawn_travel = Some(config); + Ok(true) + } + /// `PlayerList.respawn` at an anchor once its dimension is loaded around + /// it: a fresh player at the stand-up position facing the anchor and the + /// deplete sound, or, with no anchor left, the world spawn and + /// `block.minecraft.spawn.not_valid`. + pub(super) fn place_respawned(&mut self, config: RespawnConfig) -> Result<()> { + match self.find_respawn_and_use(config, true)? { + Some((position, yaw)) => { + let mut player = PlayerMotion::new(self.motion, position)?; + player.yaw = yaw; + player.head_yaw = yaw; + self.yaw = yaw; + self.pitch = 0.0; + player.pitch = 0.0; + self.eye = 1.62; + self.previous_eye = 1.62; + self.clock.reset(); + self.previous_position = position; + self.player = Some(player); + self.sway = Default::default(); + self.apply_equipment(); + // ClientboundSoundPacket at the block's corner, seeded from the level random. + let state = self + .world + .block(config.pos[0], config.pos[1], config.pos[2]); + if self.is_anchor(state) { + let _seed = self.world.random.next_long(); + let at = [ + f64::from(config.pos[0]), + f64::from(config.pos[1]), + f64::from(config.pos[2]), + ]; + self.audio + .play("minecraft:block.respawn_anchor.deplete", Some(at), 1.0, 1.0); + } + Ok(()) + } + None => { + // TeleportTransition.missingRespawnBlock: the world spawn, and + // the point is forgotten. + self.respawn_config = None; + self.system_message(Text::translate("block.minecraft.spawn.not_valid", &[])); + let dead = PlayerMotion::new(self.motion, Vec3::ZERO)?; + if self.dim != Dim::Overworld { + // A dead stand-in travels; the arrival makes a fresh player. + let mut dead = dead; + dead.set_health(0.0, false)?; + self.player = Some(dead); + self.end_portal_travel = true; + let result = self.enter_dimension(Dim::Overworld); + self.end_portal_travel = false; + self.end_travel = true; + return result; + } + self.player = None; + self.spawn_player() + } + } + } +} + +/// `RespawnPosAngle.calculateLookAtYaw`: the yaw from the position to the +/// bottom centre of the block. +fn look_at_yaw(position: Vec3, block: [i32; 3]) -> f32 { + let d = Vec3::new( + f64::from(block[0]) + 0.5 - position.x, + f64::from(block[1]) - position.y, + f64::from(block[2]) + 0.5 - position.z, + ) + .normalize(); + // Mth.atan2(z, x) * 180.0F / (float) Math.PI - 90.0: the compiled code + // multiplies by the folded float constant widened to double. + let degrees = horizon_core::geometry::trig::atan2(d.z, d.x) + * f64::from(horizon_core::geometry::trig::RAD_TO_DEG) + - 90.0; + wrap_degrees(degrees) as f32 +} +/// `Mth.wrapDegrees(double)`. +fn wrap_degrees(degrees: f64) -> f64 { + let mut d = degrees % 360.0; + if d >= 180.0 { + d -= 360.0; + } + if d < -180.0 { + d += 360.0; + } + d +} diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 96a4dc6c4..1de93e862 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -261,6 +261,16 @@ impl Game<'_> { self.toggles.respawn(); self.remote_respawn(); } + Some(0) if self.respawn_config.is_some() => { + // LocalPlayer.respawn: KeyMapping.resetToggleKeys. + self.toggles.respawn(); + // PlayerList.respawn at the respawn anchor, once it is loaded. + self.begin_anchor_respawn()?; + self.screen = Screen::Playing; + self.ui.death_text = None; + self.spawn_player()?; + self.capture(true); + } Some(0) => { // LocalPlayer.respawn: KeyMapping.resetToggleKeys. self.toggles.respawn(); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 9892243fc..f336d432e 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -601,6 +601,7 @@ impl Items { properties: &empty, held: None, killed_by_player: false, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -662,7 +663,22 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, ) -> Vec { - let drops = self.block_drops_raw(registry, state, held, random, sequences); + self.block_drops_exploded(registry, state, held, dynamic, random, sequences, None) + } + /// `block_drops_full` for a block an explosion destroys: `explosion` + /// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`). + #[allow(clippy::too_many_arguments)] + pub fn block_drops_exploded( + &self, + registry: &BlockRegistry, + state: BlockStateId, + held: Option<&ItemStack>, + dynamic: &[ItemStack], + random: &mut impl RandomSource, + sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, + explosion: Option, + ) -> Vec { + let drops = self.block_drops_raw(registry, state, held, random, sequences, explosion); if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) { return drops; } @@ -684,6 +700,7 @@ impl Items { held: Option<&ItemStack>, random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, + explosion_radius: Option, ) -> Vec { let Some(block) = registry.state(state) else { return vec![]; @@ -713,6 +730,7 @@ impl Items { properties: &block.properties, held, killed_by_player: false, + explosion_radius, }; return ctx.evaluate(table, random); } @@ -722,6 +740,7 @@ impl Items { properties: &block.properties, held, killed_by_player: false, + explosion_radius, }; ctx.evaluate(table, random) } @@ -744,6 +763,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -775,6 +795,7 @@ impl Items { properties: &block.properties, held: None, killed_by_player: false, + explosion_radius: None, }; match table.get("random_sequence").and_then(Value::as_str) { Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)), @@ -799,6 +820,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -820,6 +842,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -859,6 +882,8 @@ struct LootContext<'a> { properties: &'a BTreeMap, held: Option<&'a ItemStack>, killed_by_player: bool, + /// `LootContextParams.EXPLOSION_RADIUS`: an explosion that decays drops. + explosion_radius: Option, } impl LootContext<'_> { /// Level of an enchantment on the tool / killer's weapon. @@ -920,7 +945,10 @@ impl LootContext<'_> { _ => return true, }; match kind { - "minecraft:survives_explosion" => true, + // ExplosionCondition: 1 / radius under a decaying explosion. + "minecraft:survives_explosion" => self + .explosion_radius + .is_none_or(|r| random.next_float() <= 1.0 / r), "minecraft:tool/can_silk_touch" => self.enchantment_level("minecraft:silk_touch") > 0, "minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"), "minecraft:inverted" => !self.condition(&c["term"], random), @@ -1205,6 +1233,15 @@ impl LootContext<'_> { } } } + // ApplyExplosionDecay: each item survives with 1 / radius. + "minecraft:explosion_decay" => { + if let Some(radius) = self.explosion_radius { + let probability = 1.0 / radius; + stack.count = (0..stack.count) + .filter(|_| random.next_float() <= probability) + .count() as u32; + } + } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { @@ -1238,6 +1275,7 @@ mod tests { properties: props, held, killed_by_player: block.is_empty(), + explosion_radius: None, } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 94b60f3b0..7a90871c2 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1732,6 +1732,9 @@ pub struct Level { pub day_time: i64, /// The player's respawn point (bed, 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`. + pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>, pub position: Option<[f64; 3]>, pub rotation: [f32; 2], pub health: f32, @@ -1924,7 +1927,18 @@ impl Level { && let Some(Tag::IntArray(pos)) = respawn.get("pos") && pos.len() == 3 { - self.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); + let dimension = + text(respawn.get("dimension")).unwrap_or_else(|| "minecraft:overworld".into()); + if dimension == "minecraft:overworld" { + 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)); + } } let mut inventory = Vec::new(); let mut inventory_components = HashMap::new(); @@ -2116,8 +2130,19 @@ impl Level { if let Some(pos) = self.position { entries.push(("Pos", doubles(&pos))); } - // A respawn point other than the world spawn (a bed). - if let Some(s) = self.spawn { + // A respawn point other than the world spawn: an anchor elsewhere, or a bed. + if let Some((dimension, block, yaw, forced)) = &self.respawn_elsewhere { + let mut respawn = vec![ + ("dimension", string(dimension)), + ("pos", Tag::IntArray(block.to_vec())), + ("yaw", Tag::Float(yaw.to_bits())), + ("pitch", Tag::Float(0f32.to_bits())), + ]; + if *forced { + respawn.push(("forced", Tag::Byte(1))); + } + entries.push(("respawn", Tag::compound(respawn))); + } else if let Some(s) = self.spawn { let block = [ s[0].floor() as i32, s[1].floor() as i32, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java index 4093c0538..077a6dbff 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -351,6 +351,28 @@ public final class VanillaBlockUpdateOracle { return attributes; } @Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return type != null ? type : OVERWORLD_TYPE; } + /** + * ServerLevel.explode without the players to send the packet to: the + * ServerExplosion runs, then the explosion sound the client plays at + * the centre is logged. + */ + @Override public void explode(Entity source, net.minecraft.world.damagesource.DamageSource damageSource, + net.minecraft.world.level.ExplosionDamageCalculator calculator, double x, double y, double z, float r, boolean fire, + net.minecraft.world.level.Level.ExplosionInteraction type, net.minecraft.core.particles.ParticleOptions small, + net.minecraft.core.particles.ParticleOptions large, net.minecraft.util.random.WeightedList blockParticles, + net.minecraft.core.Holder sound) { + java.util.function.Function, net.minecraft.world.level.Explosion.BlockInteraction> destroy = + rule -> rules.get(rule) ? net.minecraft.world.level.Explosion.BlockInteraction.DESTROY_WITH_DECAY : net.minecraft.world.level.Explosion.BlockInteraction.DESTROY; + var interaction = switch (type) { + case NONE -> net.minecraft.world.level.Explosion.BlockInteraction.KEEP; + case BLOCK -> destroy.apply(GameRules.BLOCK_EXPLOSION_DROP_DECAY); + case MOB -> rules.get(GameRules.MOB_GRIEFING) ? destroy.apply(GameRules.MOB_EXPLOSION_DROP_DECAY) : net.minecraft.world.level.Explosion.BlockInteraction.KEEP; + case TNT -> destroy.apply(GameRules.TNT_EXPLOSION_DROP_DECAY); + case TRIGGER -> net.minecraft.world.level.Explosion.BlockInteraction.TRIGGER_BLOCK; + }; + new net.minecraft.world.level.ServerExplosion(this, source, damageSource, calculator, new Vec3(x, y, z), r, fire, interaction).explode(); + if (source == null || !source.isSilent()) emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location()); + } /** The overworld (fire in an obsidian frame lights a portal here). */ @Override public net.minecraft.resources.ResourceKey dimension() { return dimensionKey != null ? dimensionKey : net.minecraft.world.level.Level.OVERWORLD; } @Override public long getOverworldClockTime() { return DAY.totalTicks(); } 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 abbd13dc4..e1c3ff4e8 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -247,10 +247,18 @@ public final class VanillaDispenserOracle { w.registries = ParityData.access; w.server.loot.delegate = ParityData.loot; VanillaBlockUpdateOracle.set(Level.class, w, "damageSources", new net.minecraft.world.damagesource.DamageSources(ParityData.access)); + if (f.has("dim") && f.get("dim").getAsString().equals("nether")) { + // The Nether's dimension type and attributes (respawn anchors work, beds explode). + if (NETHER == null) NETHER = VanillaBlockUpdateOracle.loadDimensionType(net.minecraft.world.level.dimension.BuiltinDimensionTypes.NETHER); + w.type = NETHER; + w.dimensionKey = Level.NETHER; + w.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addConstantLayer(NETHER.attributes()).build(); + } if (f.has("rules")) { for (var rule : f.getAsJsonObject("rules").entrySet()) { if (rule.getKey().equals("tnt_explodes")) w.rules.set(GameRules.TNT_EXPLODES, rule.getValue().getAsBoolean(), null); if (rule.getKey().equals("spawner_blocks_work")) w.rules.set(GameRules.SPAWNER_BLOCKS_WORK, rule.getValue().getAsBoolean(), null); + if (rule.getKey().equals("block_explosion_drop_decay")) w.rules.set(GameRules.BLOCK_EXPLOSION_DROP_DECAY, rule.getValue().getAsBoolean(), null); } } if (f.has("items")) { @@ -302,6 +310,8 @@ public final class VanillaDispenserOracle { used = use(w, origin, f.getAsJsonObject("use")); } else if (f.has("use_item")) { used = useItem(w, origin, f.getAsJsonObject("use_item")); + } else if (f.has("respawn_at")) { + used = respawnAt(w, origin, f.getAsJsonObject("respawn_at")); } else if (f.has("hopper")) { // HopperBlockEntity.pushItemsTick, once. var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin); @@ -379,6 +389,8 @@ public final class VanillaDispenserOracle { result.add("rng " + w.rng.nextLong()); } + static net.minecraft.world.level.dimension.DimensionType NETHER; + /** The player of a "use" case: its main hand, game mode and the statistics it is awarded. */ static final class User extends net.minecraft.server.level.ServerPlayer { VanillaBlockUpdateOracle.World world; @@ -506,8 +518,15 @@ public final class VanillaDispenserOracle { var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class); VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>()); VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements); - // Standing three blocks south of the clicked block, looking down at it. - var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, 3); + // Standing three blocks (or `distance`) south of the clicked block, looking down at it. + double distance = use.has("distance") ? use.get("distance").getAsDouble() : 3; + var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, distance); + if (use.has("respawn")) { + var r = use.getAsJsonArray("respawn"); + BlockPos point = new BlockPos(r.get(0).getAsInt(), r.get(1).getAsInt(), r.get(2).getAsInt()); + player.setRespawnPosition(new net.minecraft.server.level.ServerPlayer.RespawnConfig( + net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), point, 0.0F, 0.0F), false), false); + } VanillaBlockUpdateOracle.set(Entity.class, player, "position", at); VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at)); VanillaBlockUpdateOracle.set(Entity.class, player, "xRot", 90f); @@ -526,9 +545,33 @@ public final class VanillaDispenserOracle { } List out = new ArrayList<>(player.stats); out.add("held " + ParityData.canon(player.hand) + " using " + (player.using == null ? "-" : player.using)); + var respawn = player.getRespawnConfig(); + out.add("respawn " + (respawn == null ? "-" : respawn.respawnData().dimension().identifier() + " " + VanillaBlockUpdateOracle.pos(respawn.respawnData().pos()))); return out; } + /** + * ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at `pos` + * (a respawn anchor, in the Nether or not): the position, the yaw that + * looks at the block, and the charge used (a block change). + */ + 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()); + Method find = net.minecraft.server.level.ServerPlayer.class.getDeclaredMethod("findRespawnAndUseSpawnBlock", + ServerLevel.class, net.minecraft.server.level.ServerPlayer.RespawnConfig.class, boolean.class); + find.setAccessible(true); + var found = (Optional) find.invoke(null, w, config, op.get("consume").getAsBoolean()); + if (found.isEmpty()) return List.of("respawn none"); + Object angle = found.get(); + Method position = angle.getClass().getDeclaredMethod("position"); + Method yaw = angle.getClass().getDeclaredMethod("yaw"); + position.setAccessible(true); + yaw.setAccessible(true); + var p = (net.minecraft.world.phys.Vec3) position.invoke(angle); + return List.of("respawn " + num(p.x) + " " + num(p.y) + " " + num(p.z) + " " + Float.floatToRawIntBits((float) yaw.invoke(angle))); + } + /** The level's block entity positions by x, y, z. */ static List sortedEntities(VanillaBlockUpdateOracle.World w) { List out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet()); diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index f71bbbe4d..9c860ce64 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Compare a player's right click on a block with vanilla's, for items that are both food and blocks (sweet and glow berries, carrots, potatoes), for sweet -berry bushes and for spawn eggs used on a monster spawner. +berry bushes, for spawn eggs used on a monster spawner and for respawn anchors. Every case has a block at the origin, something above it, and a player three blocks south, survival or creative, hungry or full, sneaking or not, who @@ -11,12 +11,18 @@ harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and `useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn` passing bone meal on), then `ItemStack.useOn` (`BlockItem.place` with its `mayPlaceOn` rules, `BoneMealItem.useOn`, eating a consumable that could -not be placed, and `SpawnEggItem.useOn` setting a spawner's mob). Horizon runs +not be placed, and `SpawnEggItem.useOn` setting a spawner's mob). Respawn +anchors are charged with glowstone, set the respawn point in the Nether and +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. Horizon runs `use_item_as_player` on that hit in a headless game -(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, -level events, sounds, game events, the used statistic, the held stack, the -item the player started using, spawners' next spawn data, potentials and -delay, system messages and the level random afterwards. +(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, level +events, sounds, game events, the used statistic, the held stack, the item the +player started using, spawners' next spawn data, potentials and delay, the +player's respawn point, system messages and the level random afterwards. """ import json import os @@ -37,6 +43,74 @@ ITEMS = ['sweet_berries', 'sweet_berries', 'sweet_berries', 'glow_berries', 'car # What is in the way above the clicked block. ABOVE = ['air'] * 8 + ['short_grass', 'snow', 'stone', 'water', 'dead_bush', 'fern'] EGGS = ['zombie', 'skeleton', 'spider', 'cave_spider', 'pig', 'creeper', 'blaze', 'ghast', 'villager', 'bee', 'cod'] +# What stands around an anchor that explodes. +AROUND = ['stone', 'dirt', 'oak_planks', 'cobblestone', 'glass', 'obsidian', 'netherrack', 'water', 'tnt', 'oak_log', + 'grass_block', 'soul_sand', 'gravel', 'crying_obsidian'] + + +STAND = ['air'] * 6 + ['stone', 'stone', 'oak_slab', 'snow', 'lava', 'magma_block', 'fire', 'cactus', 'water', + 'ladder', 'oak_trapdoor', 'short_grass', 'white_carpet', 'campfire', 'sweet_berry_bush', + 'oak_fence', 'powder_snow', 'farmland', 'soul_sand', 'cobweb', 'end_portal'] + + +def respawn_case(rng, states, case): + """Respawning at an anchor with blocks around it.""" + charges = rng.choice([0, 1, 1, 2, 4]) + cells = [[0, 0, 0, states.get('respawn_anchor', charges=str(charges))]] + for dy in (-2, -1, 0, 1, 2): + for dx in range(-1, 2): + for dz in range(-1, 2): + if (dx, dy, dz) == (0, 0, 0): + continue + if dy == -1 or dy == -2: + name = rng.choice(['stone'] * 6 + STAND) + else: + name = rng.choice(['air'] * 3 + STAND) + if name == 'air': + continue + state = states.any(rng, name) if name in ('oak_trapdoor', 'oak_slab', 'snow', 'campfire', 'water', 'ladder') else states.get(name) + cells.append([dx, dy, dz, state]) + if rng.random() < 0.6: + case['dim'] = 'nether' + case['respawn_at'] = {'forced': rng.random() < 0.2, 'consume': rng.random() < 0.8} + case['cells'] = cells + + +def anchor_case(rng, states, case): + """A respawn anchor clicked in the Nether or the Overworld, with blocks + and water around it.""" + charges = rng.choice([0, 0, 1, 2, 3, 4, 4]) + cells = [[0, 0, 0, states.get('respawn_anchor', charges=str(charges))], + [0, -1, 0, states.get(rng.choice(['netherrack', 'stone', 'soul_sand', 'obsidian', 'soul_soil']))]] + taken = {(0, 0, 0), (0, -1, 0)} + for _ in range(rng.choice([0, 3, 8, 20, 40])): + p = (rng.randrange(-3, 4), rng.randrange(-2, 3), rng.randrange(-3, 4)) + if p in taken: + continue + taken.add(p) + name = rng.choice(AROUND) + state = states.any(rng, 'water') if name == 'water' and rng.random() < 0.5 else states.get(name) + cells.append([*p, state]) + if rng.random() < 0.2: + # Water that would flow into the anchor's place. + d = rng.choice([(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1), (0, 1, 0)]) + cells = [c for c in cells if tuple(c[:3]) != d] + cells.append([*d, states.any(rng, 'water') if rng.random() < 0.4 else states.get('water')]) + nether = rng.random() < 0.5 + if nether: + case['dim'] = 'nether' + item = rng.choice(['glowstone'] * 5 + ['apple', '-', 'stone', 'glowstone_dust']) + count = rng.choice([1, 1, 16, 64]) + use = {'item': '-' if item == '-' else d_plain(item, count), 'creative': rng.random() < 0.2, + 'sneaking': rng.random() < 0.1, 'food': 20, + # Away from the blast: the stand-in player is not an entity of the level. + 'distance': 3 if nether else 12} + if rng.random() < 0.3: + use['respawn'] = rng.choice([[0, 0, 0], [5, 0, 5]]) + if rng.random() < 0.2: + case['rules'] = {'block_explosion_drop_decay': False} + case['use_item'] = use + case['cells'] = cells def cases(facts, count, seed): @@ -46,6 +120,18 @@ def cases(facts, count, seed): case = {**h.environment(rng), 'pos': [0, 0, 0]} case.pop('raining', None) case.pop('thundering', None) + if rng.random() < 0.1: + 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'] = [] + case['mode'] = 'dispense' + yield case + continue cells = [] item = rng.choice(ITEMS) if rng.random() < 0.15: @@ -83,8 +169,14 @@ def cases(facts, count, seed): yield case +def d_plain(item, count): + return d.plain(item, count) + + def kind(case, facts): first = facts.states[case['cells'][0][3]][0].split(':')[1] + if 'respawn_at' in case: + return f'respawn at {first}' item = case['use_item']['item'] item = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand' return f'{item} on {first}' @@ -119,13 +211,15 @@ def main(): rust = h.split_cases((work / 'rust.txt').read_text(), ignore) assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) groups, errors = {}, {} - planted = eaten = 0 + planted = eaten = respawned = exploded = 0 for case, a, b in zip(all_cases, native, rust): if a and a[0].startswith('error'): errors.setdefault(a[0], []).append(case) continue planted += any(line.startswith('set 0,1,0') for line in a) eaten += any(line.startswith('held') and not line.endswith('using -') for line in a) + respawned += any(line.startswith('respawn ') and line != 'respawn none' and 'respawn_at' in case for line in a) + exploded += any(line.endswith(' minecraft:explode') for line in a) if not d.same(a, b): groups.setdefault(kind(case, facts), []).append((case, a, b)) for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])): @@ -133,13 +227,14 @@ def main(): for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])): print(f'{name}: {len(entries)} differing') for case, a, b in entries[:args.show]: - print(' case ' + d.describe(case, facts) + ' use=' + json.dumps(case['use_item'])) + print(' case ' + d.describe(case, facts) + ' use=' + json.dumps(case.get('use_item', case.get('respawn_at')))) print(' native ' + ' | '.join(sorted(a))) print(' rust ' + ' | '.join(sorted(b))) total = sum(len(v) for v in groups.values()) skipped = sum(len(v) for v in errors.values()) print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors); ' - f'vanilla planted in {planted} and started eating in {eaten}') + f'vanilla planted in {planted}, started eating in {eaten}, exploded {exploded} times and found a respawn ' + f'spot in {respawned}') h.finish(total + skipped)