diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index a5c61c065..5b9258aeb 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -245,6 +245,10 @@ fn main() -> Result<()> { )?; // The oracle runs block-inside effects only in "snow_tick". player.block_effects = false; + // Entity.portalCooldown and portalProcess, and the entry of the last + // portal_tick that went through. + let mut portal = horizon_client::nether_portal::PortalState::default(); + let mut travel: Option = None; for op in f["ops"].as_array().unwrap() { let mut world = MotionWorld { player: &mut player, @@ -442,6 +446,14 @@ fn main() -> Result<()> { world.player.freeze_immune = boots; } "frozen" => world.player.ticks_frozen = op["value"].as_i64().unwrap() as i32, + "portal_tick" => { + // Entity.handlePortal without the destination: players wait + // the creative delay (0) when invulnerable, else 80 ticks. + let creative = op["creative"].as_bool().unwrap(); + let transition = if creative { 0 } else { 80 }; + let alive = !world.player.health.dead_or_dying(); + travel = portal.handle(alive, transition, 10); + } "weaving" => world.player.status.weaving = op["value"].as_bool().unwrap(), "flying" => { let flying = op["value"].as_bool().unwrap(); @@ -515,6 +527,14 @@ fn main() -> Result<()> { } _ => return Err("unknown motion operation".into()), } + // NetherPortalBlock.entityInside: canUsePortal, setAsInsidePortal. + for e in &player.events { + if let MotionEvent::InsidePortal { pos } = e + && !player.health.dead_or_dying() + { + portal.set_inside(*pos, 10); + } + } let check_block = scene.block(25, 3, 25); snapshot(&mut out, &player)?; let stuck = player.stuck_multiplier; @@ -529,6 +549,18 @@ fn main() -> Result<()> { stuck.y.to_bits(), stuck.z.to_bits() )?; + writeln!( + out, + "portal {} {} {}", + portal.cooldown, + portal.process.map_or("none".into(), |p| format!( + "{},{},{} {} {}", + p.entry.x, p.entry.y, p.entry.z, p.time, p.inside + )), + travel + .take() + .map_or("-".into(), |t| format!("{},{},{}", t.x, t.y, t.z)) + )?; let h = &player.health; let canonical = |v: f32| { if v.is_nan() { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 51948cc72..082967726 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -29,10 +29,10 @@ pub fn position(tag: &Tag) -> Option { pub fn uuid(tag: &Tag) -> Option<[i32; 4]> { uuid_from_tag(tag.get("UUID")) } -fn motion(tag: &Tag) -> Vec3 { +pub fn motion(tag: &Tag) -> Vec3 { read_doubles::<3>(tag.get("Motion")).map_or(Vec3::ZERO, |m| Vec3::new(m[0], m[1], m[2])) } -fn rotation(tag: &Tag) -> [f32; 2] { +pub fn rotation(tag: &Tag) -> [f32; 2] { read_doubles::<2>(tag.get("Rotation")).map_or([0.0; 2], |r| [r[0] as f32, r[1] as f32]) } fn flag(tag: &Tag, key: &str) -> bool { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a0d350a6b..29a3d5a14 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -70,6 +70,7 @@ mod names; mod natural_spawning; mod nautili; mod net_harness; +mod nether_portal; mod options; mod packs; mod paintings; @@ -765,8 +766,8 @@ struct Game<'a> { world_root: PathBuf, /// A player carried through a portal, re-placed once the destination loads. travelling: Option<(PlayerMotion, Vec3)>, - portal_ticks: u32, - portal_cooldown: u32, + /// Nether portals: the player's, items' and mobs' (game/nether_portal.rs). + portals: nether_portal::Portals, /// The pending travel goes through an End portal (EndPortalBlock destinations). end_travel: bool, /// The next enter_dimension call comes from an End portal. @@ -2836,6 +2837,7 @@ impl Game<'_> { } MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), + MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos), _ => {} } } @@ -2923,6 +2925,7 @@ impl Game<'_> { horizon_client::spans::time("tick_rockets", || self.tick_rockets()); } if running { + horizon_client::spans::time("entity_portals", || self.handle_entity_portals()); horizon_client::spans::time("tick_items", || self.tick_items()); } horizon_client::spans::time("spawn_loaded_entities", || self.spawn_loaded_entities()); @@ -2930,11 +2933,15 @@ impl Game<'_> { horizon_client::spans::time("tick_mobs", || self.tick_mobs())?; horizon_client::spans::time("recheck_golem_openers", || self.recheck_golem_openers()); horizon_client::spans::time("tick_experience", || self.tick_experience()); + horizon_client::spans::time("entity_portals", || { + self.find_entity_portals(); + self.resolve_arrivals(); + }); } horizon_client::spans::time("tick_lan", || self.tick_lan()); horizon_client::spans::time("tick_hand", || self.tick_hand()); horizon_client::spans::time("tick_sleep", || self.tick_sleep()); - horizon_client::spans::time("tick_portal", || self.tick_portal())?; + horizon_client::spans::time("tick_portal", || self.tick_nether_portal())?; if running { horizon_client::spans::time("tick_end", || self.tick_end())?; } @@ -5546,6 +5553,7 @@ impl Game<'_> { self.player_spawn = None; self.mobs.clear(); self.creatures.reset_trader(); + self.portals = Default::default(); self.arrows.clear(); self.dropped.clear(); self.particles.clear(); @@ -5703,7 +5711,6 @@ impl Game<'_> { self.orbs.clear(); self.mining = None; self.travelling = Some((player, destination)); - self.portal_cooldown = 300; self.end_travel = (target == Dim::End || from_end) && self.end_portal_travel; if let Some(r) = self.renderer.as_mut() { r.clear_sections(); @@ -5812,138 +5819,9 @@ impl Game<'_> { } Ok(false) } - /// PortalForcer: reuse a nearby portal, else build a 2x3 obsidian portal. - fn place_after_travel(&mut self, mut player: PlayerMotion, target: Vec3) -> Result<()> { - let (tx, tz) = (target.x.floor() as i32, target.z.floor() as i32); - let radius = if self.dim == Dim::Nether { 16 } else { 32 }; - let (min_y, max_y) = if self.dim == Dim::Nether { - (1, 126) - } else { - (MIN_Y + 1, MIN_Y + HEIGHT - 3) - }; - let portal_name = "minecraft:nether_portal"; - let mut best: Option<(i64, [i32; 3])> = None; - for z in tz - radius..=tz + radius { - for x in tx - radius..=tx + radius { - if !self.world.loaded(x, z) { - continue; - } - for y in min_y..max_y { - if &*self.res.facts.get(self.world.block(x, y, z)).name == portal_name - && &*self.res.facts.get(self.world.block(x, y - 1, z)).name != portal_name - { - let d = i64::from(x - tx).pow(2) - + i64::from(z - tz).pow(2) - + i64::from(y - target.y as i32).pow(2); - if best.is_none_or(|b| d < b.0) { - best = Some((d, [x, y, z])); - } - } - } - } - } - let spot = match best { - Some((_, p)) => p, - None => { - // Build: obsidian frame 4 wide, 5 tall, with a floor, carved into the terrain. - let y = (target.y.floor() as i32).clamp(min_y + 1, max_y - 5); - let set = |g: &mut Self, p: [i32; 3], name: &str| -> Result<()> { - if let Some(id) = g.res.assets.registry.default_state(name) { - g.world.set(p[0], p[1], p[2], id)?; - } - Ok(()) - }; - for dz in -1..=1 { - for dx in -1..=2 { - set(self, [tx + dx, y - 1, tz + dz], "minecraft:obsidian")?; - for dy in 0..4 { - set(self, [tx + dx, y + dy, tz + dz], "minecraft:air")?; - } - } - } - for w in -1..=2 { - for h in -1..=3 { - if w == -1 || w == 2 || h == -1 || h == 3 { - set(self, [tx + w, y + h, tz], "minecraft:obsidian")?; - } - } - } - self.try_light_portal([tx, y, tz])?; - [tx, y, tz] - } - }; - player.position = Vec3::new( - f64::from(spot[0]) + 0.5, - f64::from(spot[1]), - f64::from(spot[2]) + 0.5, - ); - player.velocity = Vec3::ZERO; - self.previous_position = player.position; - self.player = Some(player); - self.sway = Default::default(); - self.apply_equipment(); - let at = [f64::from(spot[0]), f64::from(spot[1]), f64::from(spot[2])]; - self.audio - .play("minecraft:block.portal.travel", Some(at), 0.25, 1.0); - Ok(()) - } - fn tick_portal(&mut self) -> Result<()> { - let Some(p) = self.player.as_ref() else { - return Ok(()); - }; - let w = f64::from(p.dimensions.width) / 2.0; - let (lo, hi) = ( - [p.position.x - w, p.position.y, p.position.z - w], - [ - p.position.x + w, - p.position.y + f64::from(p.dimensions.height), - p.position.z + w, - ], - ); - let mut inside = false; - for x in lo[0].floor() as i32..=hi[0].floor() as i32 { - for y in lo[1].floor() as i32..=hi[1].floor() as i32 { - for z in lo[2].floor() as i32..=hi[2].floor() as i32 { - if &*self.res.facts.get(self.world.block(x, y, z)).name - == "minecraft:nether_portal" - { - inside = true; - } - } - } - } - if !inside { - self.portal_ticks = 0; - self.portal_cooldown = self.portal_cooldown.saturating_sub(1); - return Ok(()); - } - if self.portal_cooldown > 0 { - return Ok(()); - } - if self.portal_ticks == 0 { - let at = self.eye_position(); - self.audio.play( - "minecraft:block.portal.trigger", - at, - 0.25, - self.world.random.next_float() * 0.4 + 0.8, - ); - } - self.portal_ticks += 1; - // Player.getPortalWaitTime: 80 ticks, or 1 when invulnerable (creative). - let wait = if self.creative { 1 } else { 80 }; - if self.portal_ticks >= wait { - self.portal_ticks = 0; - // NetherPortalBlock: the Nether leads to the Overworld, anywhere else to the Nether. - let target = if self.dim == Dim::Nether { - Dim::Overworld - } else { - Dim::Nether - }; - self.end_portal_travel = false; - self.enter_dimension(target)?; - } - Ok(()) + /// Arrival through a nether portal, once the destination is loaded. + fn place_after_travel(&mut self, player: PlayerMotion, target: Vec3) -> Result<()> { + self.arrive_through_nether_portal(player, target) } /// Leaving the game with a world open (window closed, Quit, `quit`): /// menu items go back (Player.closeContainer), then the world is saved, @@ -7505,6 +7383,7 @@ impl Game<'_> { self.save_raids(); self.save_fight(); self.save_wandering_trader(); + self.save_portal_arrivals(); self.save_stats(); self.save_advancements(); self.save_scoreboard(); @@ -9007,8 +8886,7 @@ pub fn run() -> Result<()> { dim: Dim::Overworld, world_root: PathBuf::new(), travelling: None, - portal_ticks: 0, - portal_cooldown: 0, + portals: Default::default(), end_travel: false, end_portal_travel: false, end: Default::default(), diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index ded41fb3d..fa60228de 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -389,7 +389,7 @@ impl Game<'_> { } } if portal { - if self.portal_cooldown == 0 { + if self.portals.player.cooldown == 0 { let target = if self.dim == Dim::End { Dim::Overworld } else { @@ -400,10 +400,10 @@ impl Game<'_> { self.end_portal_travel = false; result?; // Player.getDimensionChangingDelay. - self.portal_cooldown = 10; + self.portals.player.cooldown = 10; } else { // Entity.setAsInsidePortal while cooling down restarts the cooldown. - self.portal_cooldown = 10; + self.portals.player.cooldown = 10; } } else if let Some(g) = gateway && self.end.gateway_cooldown == 0 @@ -440,7 +440,7 @@ impl Game<'_> { ) -> Result<()> { self.end_travel = false; // Player.getDimensionChangingDelay (enter_dimension uses the Nether portal value). - self.portal_cooldown = 10; + self.portals.player.cooldown = 10; if player.health.dead_or_dying() { // Respawning out of the End: a fresh player at the spawn. player = PlayerMotion::new(self.motion, target)?; diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs new file mode 100644 index 000000000..a6296d09b --- /dev/null +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -0,0 +1,722 @@ +//! Nether portals for the player and the other entities: +//! `Entity.setAsInsidePortal` / `handlePortal` with `PortalProcessor`, +//! `NetherPortalBlock.getPortalTransitionTime` and `getPortalDestination` +//! (`PortalForcer` through `horizon_world::level::portal_travel`), and +//! `LocalPlayer.handlePortalTransitionEffect`. +//! +//! Only one dimension is loaded at a time. The player's destination is found +//! once the other dimension has loaded around it. An item or mob that goes +//! through waits as an `Arrival` (its saved compound and where it stood in its +//! portal) until the player is in that dimension and its exit is loaded. +use super::{Dim, Game, Screen}; +use horizon_client::Result; +use horizon_client::nether_portal::PortalState; +use horizon_core::{ + geometry::{Axis, Vec3}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::{ + level::portal_travel::{ + BorderBounds, FoundRectangle, closest_portal, collision_free_position, exit_position, + largest_rectangle_around, relative_position, + }, + nbt::Tag, +}; +use std::collections::HashMap; + +/// `Player.getDimensionChangingDelay`. +pub(super) const PLAYER_DELAY: i32 = 10; +/// `Entity.getDimensionChangingDelay`. +const ENTITY_DELAY: i32 = 300; + +/// Where in its portal a traveller stood, and where its exit is to be found. +#[derive(Clone, Copy, Debug)] +pub(super) struct Plan { + pub(super) dim: Dim, + /// The border-clamped, scaled position (`approximateExitPos`). + pub(super) approximate: BlockPos, + entry_x_axis: bool, + offset: Vec3, + width: f32, + height: f32, +} + +/// An entity on its way to a dimension that isn't loaded. +#[derive(Clone, Debug)] +struct Arrival { + plan: Plan, + tag: Tag, +} + +/// The nether portal state of the world (`Game::portals`). +#[derive(Default)] +pub(super) struct Portals { + /// The player's. + pub(super) player: PortalState, + /// The player's travel, while the destination loads. + pub(super) travel: Option, + /// `LocalPlayer.portalProcess.isInsidePortalThisTick`. + client_inside: bool, + /// Items and mobs, by entity id. + entities: HashMap, + /// Positions before this tick's moves, by entity id. + before: HashMap, + arrivals: Vec, + loaded: bool, + dirty: bool, +} + +fn rotate_y(v: Vec3, degrees: f32) -> Vec3 { + // Vec3.yRot((float)Math.toRadians(degrees)) + let angle = f64::from(degrees.to_radians()); + let (cos, sin) = ( + f64::from(horizon_core::geometry::trig::cos(angle)), + f64::from(horizon_core::geometry::trig::sin(angle)), + ); + Vec3::new(v.x * cos + v.z * sin, v.y, v.z * cos - v.x * sin) +} +fn doubles(values: [f64; 3]) -> Tag { + Tag::List(values.iter().map(|v| Tag::Double(v.to_bits())).collect()) +} + +impl Game<'_> { + /// The world border's extent. + fn border_bounds(&self) -> BorderBounds { + let [min_x, min_z, max_x, max_z] = self.border.bounds(); + BorderBounds { + min_x, + min_z, + max_x, + max_z, + } + } + /// `ServerLevel.isAllowedToEnterPortal`. + fn may_enter(&self, target: Dim) -> bool { + target != Dim::Nether || self.ui.rules.bool("allow_entering_nether_using_portals") + } + /// The plan of an entity of `width` by `height` at `at` going through the + /// portal at `entry` (`getDimensionTransitionFromExit` and the scaled, + /// clamped exit of `getPortalDestination`). + fn portal_plan( + &self, + entry: BlockPos, + at: Vec3, + width: f32, + height: f32, + reset_forward: bool, + ) -> Plan { + let target = if self.dim == Dim::Nether { + Dim::Overworld + } else { + Dim::Nether + }; + let state = self.world.block(entry.x, entry.y, entry.z); + let b = &self.res.behaviours; + let (entry_x_axis, offset) = match b.portal_axis(state) { + Some(x_axis) => { + let area = largest_rectangle_around( + entry, + if x_axis { Axis::X } else { Axis::Z }, + 21, + Axis::Y, + 21, + |p| self.world.block(p.x, p.y, p.z) == state, + ); + let mut offset = relative_position(area, x_axis, at, width, height); + if reset_forward { + offset.z = 0.0; + } + (x_axis, offset) + } + None => (true, Vec3::new(0.5, 0.0, 0.0)), + }; + // DimensionType.getTeleportationScale: 8 out of the Nether, 1/8 into it. + let scale = if self.dim == Dim::Nether { + 8.0 + } else { + 1.0 / 8.0 + }; + Plan { + dim: target, + approximate: self.border_bounds().clamp(at.x * scale, at.y, at.z * scale), + entry_x_axis, + offset, + width, + height, + } + } + /// The nether portal blocks of the chunks within `radius` of `center` + /// (the points of interest `PortalForcer` searches): loaded chunks as + /// they are, the others as saved; chunks never generated have none. + fn portal_blocks(&self, center: BlockPos, radius: i32) -> Vec { + let b = &self.res.behaviours; + let chunk_radius = radius.div_euclid(16) + 1; + let (cx, cz) = (center.x >> 4, center.z >> 4); + let mut out = Vec::new(); + for z in cz - chunk_radius..=cz + chunk_radius { + for x in cx - chunk_radius..=cx + chunk_radius { + let saved; + let chunk = match self.world.chunks.get(&(x, z)) { + Some(c) => &**c, + None => match self + .save + .load(x, z, self.res.assets.registry, &self.res.biomes) + { + Some(c) => { + saved = c; + &saved + } + None => continue, + }, + }; + for (s, section) in chunk.sections.iter().enumerate() { + if !section.blocks.maybe_has(|v| { + b.portal_axis(horizon_world::registry::BlockStateId(v)) + .is_some() + }) { + continue; + } + let base = horizon_client::chunk::MIN_Y + 16 * s as i32; + for y in base..base + 16 { + for lz in 0..16 { + for lx in 0..16 { + let (wx, wz) = (x * 16 + lx, z * 16 + lz); + if b.portal_axis(chunk.block(wx, y, wz)).is_some() { + out.push(BlockPos::new(wx, y, wz)); + } + } + } + } + } + } + } + out + } + /// The exit portal of `plan` in the loaded dimension: the closest one + /// within reach, else one built by `PortalForcer.createPortal`. + fn nether_exit_portal(&mut self, plan: &Plan) -> Option { + let to_nether = plan.dim == Dim::Nether; + let radius = if to_nether { 16 } else { 128 }; + let border = self.border_bounds(); + let portals = self.portal_blocks(plan.approximate, radius); + let (min_section, max_section) = if to_nether { (0, 15) } else { (-4, 19) }; + let found = closest_portal( + &portals, + plan.approximate, + to_nether, + &border, + min_section, + max_section, + ); + if let Some(found) = found { + let state = self.world.block(found.x, found.y, found.z); + let x_axis = self.res.behaviours.portal_axis(state).unwrap_or(true); + return Some(largest_rectangle_around( + found, + if x_axis { Axis::X } else { Axis::Z }, + 21, + Axis::Y, + 21, + |p| self.world.block(p.x, p.y, p.z) == state, + )); + } + let logical = if to_nether { 128 } else { 384 }; + let (approximate, x_axis) = (plan.approximate, plan.entry_x_axis); + let created = self.with_level(|b, level, ticks| { + b.create_portal(level, ticks, approximate, x_axis, &border, logical) + }); + let _ = self.process_level_events(); + created + } + /// `NetherPortalBlock.createDimensionTransition`: the arrival position + /// and the yaw turned by. + fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) { + let b = &self.res.behaviours; + let corner = exit.min_corner; + let exit_x_axis = b + .portal_axis(self.world.block(corner.x, corner.y, corner.z)) + .unwrap_or(true); + let (bottom, rotation) = exit_position( + exit, + exit_x_axis, + plan.entry_x_axis, + plan.offset, + plan.width, + plan.height, + ); + let border = self.border_bounds(); + let at = collision_free_position(bottom, plan.width, plan.height, &border, |p| { + b.collision_shape(self.world.block(p.x, p.y, p.z)) + .map(|s| s.moved(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)))) + }); + (at, rotation) + } + + // ---- the player ---- + + /// `NetherPortalBlock.entityInside` for the player: `canUsePortal`, then + /// `setAsInsidePortal` (and the client's own, which drives the effect). + pub(super) fn player_inside_nether_portal(&mut self, pos: BlockPos) { + let alive = self + .player + .as_ref() + .is_some_and(|p| !p.health.dead_or_dying()); + if !alive || self.riding.is_some() || self.sleeping.is_some() { + return; + } + self.portals.player.set_inside(pos, PLAYER_DELAY); + self.portals.client_inside = true; + } + /// `ServerPlayer.handlePortal` (not while changing dimension: there is no + /// player then). Players wait `players_nether_portal_default_delay` + /// ticks, or the creative delay with invulnerable abilities. + pub(super) fn tick_nether_portal(&mut self) -> Result<()> { + // A server's portals are its own. + if self.remote.is_some() { + return Ok(()); + } + let Some(p) = self.player.as_ref() else { + return Ok(()); + }; + if self.travelling.is_some() { + return Ok(()); + } + let allowed = !p.health.dead_or_dying() && self.riding.is_none() && self.sleeping.is_none(); + let rule = if p.invulnerable { + "players_nether_portal_creative_delay" + } else { + "players_nether_portal_default_delay" + }; + let transition = self.ui.rules.int(rule).max(0); + let Some(entry) = self + .portals + .player + .handle(allowed, transition, PLAYER_DELAY) + else { + return Ok(()); + }; + let Some(p) = self.player.as_ref() else { + return Ok(()); + }; + let plan = self.portal_plan( + entry, + p.position, + p.dimensions.width, + p.dimensions.height, + true, + ); + if !self.may_enter(plan.dim) { + return Ok(()); + } + self.portals.travel = Some(plan); + self.end_portal_travel = false; + self.enter_dimension(plan.dim)?; + // The destination is all on disk now: load around the portal its + // points of interest lead to, or the approximate exit. + let to_nether = plan.dim == Dim::Nether; + let portals = self.portal_blocks(plan.approximate, if to_nether { 16 } else { 128 }); + let (min_section, max_section) = if to_nether { (0, 15) } else { (-4, 19) }; + let border = self.border_bounds(); + let found = closest_portal( + &portals, + plan.approximate, + to_nether, + &border, + min_section, + max_section, + ); + let centre = found.unwrap_or(plan.approximate); + if let Some((_, target)) = self.travelling.as_mut() { + *target = Vec3::new( + f64::from(centre.x) + 0.5, + f64::from(centre.y), + f64::from(centre.z) + 0.5, + ); + } + Ok(()) + } + /// The player's arrival once the destination has loaded around the + /// approximate exit: the waiting entities first, then the exit portal + /// (found or built), the position in it, the turned yaw and motion, and + /// `TeleportTransition.PLAY_PORTAL_SOUND` (level event 1032). + pub(super) fn arrive_through_nether_portal( + &mut self, + mut player: horizon_client::motion::PlayerMotion, + target: Vec3, + ) -> Result<()> { + self.resolve_arrivals(); + let plan = self.portals.travel.take(); + let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan)); + let (position, rotation) = match (plan, exit) { + (Some(plan), Some(exit)) => self.arrival(&plan, exit), + _ => (target, 0.0), + }; + player.position = position; + // Relative.ROTATION and Relative.DELTA: the yaw turns, the motion + // turns with it. + player.yaw += rotation; + player.head_yaw += rotation; + self.yaw += rotation; + player.velocity = rotate_y(player.velocity, -rotation); + self.previous_position = player.position; + self.player = Some(player); + self.sway = Default::default(); + self.apply_equipment(); + let pitch = self.world.random.next_float() * 0.4 + 0.8; + self.audio + .play("minecraft:block.portal.travel", None, 0.25, pitch); + Ok(()) + } + /// `LocalPlayer.handlePortalTransitionEffect`: whether the confusion + /// effect grows this tick. Entering a portal closes screens other than + /// the chat and death screens and plays `block.portal.trigger` when the + /// effect starts from nothing. + pub(super) fn client_portal_effect(&mut self) -> bool { + if !std::mem::take(&mut self.portals.client_inside) { + return false; + } + match self.screen { + Screen::Playing | Screen::Chat | Screen::Dead => {} + Screen::Inventory | Screen::Creative => { + self.close_container(); + self.carried = None; + self.screen = Screen::Playing; + self.capture(true); + } + _ => { + self.screen = Screen::Playing; + self.capture(true); + } + } + if self.res.screen_fx.portal == 0.0 { + let pitch = self.world.random.next_float() * 0.4 + 0.8; + self.audio + .play("minecraft:block.portal.trigger", None, 0.25, pitch); + } + true + } + + // ---- other entities ---- + + /// Positions before the entities move this tick, and `Entity.handlePortal` + /// at the start of their tick: an item or mob that stayed in a portal + /// goes through (transition time 0) and waits for its dimension. + pub(super) fn handle_entity_portals(&mut self) { + if self.remote.is_some() { + return; + } + self.load_portal_arrivals(); + let mut leaving: Vec<(u32, BlockPos)> = Vec::new(); + self.portals.before.clear(); + for e in &self.dropped { + self.portals.before.insert(e.id, e.position); + } + for m in &self.mobs { + self.portals.before.insert(m.id, m.position); + } + let ids: Vec<(u32, bool)> = self + .dropped + .iter() + .map(|e| (e.id, true)) + .chain(self.mobs.iter().map(|m| (m.id, self.mob_can_use_portal(m)))) + .collect(); + let present: std::collections::HashSet = ids.iter().map(|(id, _)| *id).collect(); + self.portals.entities.retain(|id, _| present.contains(id)); + for (id, allowed) in ids { + let Some(state) = self.portals.entities.get_mut(&id) else { + continue; + }; + if let Some(entry) = state.handle(allowed, 0, ENTITY_DELAY) { + leaving.push((id, entry)); + } + if state.cooldown == 0 && state.process.is_none() { + self.portals.entities.remove(&id); + } + } + for (id, entry) in leaving { + self.send_through_portal(id, entry); + } + } + /// `Entity.load`: the saved `PortalCooldown` (an entity that just came + /// through stands in its exit portal for 300 ticks without going back). + pub(super) fn restore_portal_cooldown(&mut self, id: u32, tag: &Tag) { + if let Some(Tag::Int(cooldown)) = tag.get("PortalCooldown") + && *cooldown > 0 + { + self.portals.entities.insert( + id, + PortalState { + cooldown: *cooldown, + process: None, + }, + ); + } + } + /// `canUsePortal(false)` of a mob: alive, riding nothing, not asleep, + /// not carrying the player, and not a boss that never travels. + fn mob_can_use_portal(&self, m: &horizon_client::mobs::Mob) -> bool { + use horizon_client::mobs::Species; + m.alive() + && m.extra.mount.is_none() + && self.riding != Some(m.id) + && m.species() != Species::Wither + } + /// `NetherPortalBlock.entityInside` for the items and mobs that moved this + /// tick: the portal blocks their box swept through. + pub(super) fn find_entity_portals(&mut self) { + if self.remote.is_some() { + return; + } + let mut inside: Vec<(u32, BlockPos)> = Vec::new(); + let items: Vec<(u32, Vec3, f32, f32)> = self + .dropped + .iter() + .map(|e| (e.id, e.position, 0.25, 0.25)) + .collect(); + let mobs: Vec<(u32, Vec3, f32, f32)> = self + .mobs + .iter() + .filter(|m| self.mob_can_use_portal(m)) + .map(|m| (m.id, m.position, m.width(), m.height())) + .collect(); + for (id, to, width, height) in items.into_iter().chain(mobs) { + let from = self.portals.before.get(&id).copied().unwrap_or(to); + if let Some(pos) = self.swept_portal(from, to, width, height) { + inside.push((id, pos)); + } + } + for (id, pos) in inside { + self.portals + .entities + .entry(id) + .or_default() + .set_inside(pos, ENTITY_DELAY); + } + } + /// The first nether portal block an entity box swept through + /// (`Entity.checkInsideBlocks`, whose first portal sets the entry). + fn swept_portal(&self, from: Vec3, to: Vec3, width: f32, height: f32) -> Option { + let half = f64::from(width) / 2.0; + let bounds = horizon_core::geometry::Aabb::new( + Vec3::new(to.x - half, to.y, to.z - half), + Vec3::new(to.x + half, to.y + f64::from(height), to.z + half), + ) + .deflate(Vec3::new( + f64::from(1.0e-5_f32), + f64::from(1.0e-5_f32), + f64::from(1.0e-5_f32), + )); + let mut found = None; + let _ = horizon_core::geometry::sweep_intersected_blocks( + from, + to, + bounds, + 1_000_000, + |p, _| { + if self + .res + .behaviours + .portal_axis(self.world.block(p.x, p.y, p.z)) + .is_some() + { + found = Some(p); + return false; + } + true + }, + ); + found + } + /// `Entity.teleportCrossDimension` away from the loaded dimension: the + /// entity is saved and removed, and waits for its dimension to load. + fn send_through_portal(&mut self, id: u32, entry: BlockPos) { + if let Some(i) = self.dropped.iter().position(|e| e.id == id) { + let e = &self.dropped[i]; + let plan = self.portal_plan(entry, e.position, 0.25, 0.25, false); + if !self.may_enter(plan.dim) { + return; + } + let uuid = self.uuid_for(id); + let tag = horizon_client::entity_nbt::item_entity_to_nbt( + &self.dropped[i], + uuid, + self.persist_raw(id), + ); + self.dropped.remove(i); + self.forget_entity(id); + self.portals.arrivals.push(Arrival { plan, tag }); + self.portals.dirty = true; + } else if let Some(i) = self.mobs.iter().position(|m| m.id == id) { + let m = &self.mobs[i]; + let plan = self.portal_plan(entry, m.position, m.width(), m.height(), true); + if !self.may_enter(plan.dim) { + return; + } + let mut tag = self.mob_tree_nbt(i); + // Entity.removeAfterChangingDimensions drops the leash. + if let Tag::Compound(c) = &mut tag { + c.remove(&"leash".into()); + } + let mut gone = vec![id]; + let mut k = 0; + while k < gone.len() { + let v = gone[k]; + gone.extend( + self.mobs + .iter() + .filter(|m| m.extra.mount == Some(v)) + .map(|m| m.id), + ); + k += 1; + } + self.mobs.retain(|m| !gone.contains(&m.id)); + for g in gone { + self.forget_entity(g); + } + self.portals.arrivals.push(Arrival { plan, tag }); + self.portals.dirty = true; + } + } + /// Entities waiting for the loaded dimension whose exit area is loaded: + /// their exit portal (found or built), position, turned yaw and motion, + /// and portal cooldown; they join the world with the chunk entities. + pub(super) fn resolve_arrivals(&mut self) { + if self.remote.is_some() { + return; + } + let mut i = 0; + while i < self.portals.arrivals.len() { + let plan = self.portals.arrivals[i].plan; + let (cx, cz) = (plan.approximate.x >> 4, plan.approximate.z >> 4); + let ready = plan.dim == self.dim + && (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))); + if !ready { + i += 1; + continue; + } + let Arrival { plan, mut tag } = self.portals.arrivals.remove(i); + self.portals.dirty = true; + let Some(exit) = self.nether_exit_portal(&plan) else { + continue; + }; + let (at, rotation) = self.arrival(&plan, exit); + let motion = rotate_y(horizon_client::entity_nbt::motion(&tag), -rotation); + let [yaw, pitch] = horizon_client::entity_nbt::rotation(&tag); + if let Tag::Compound(c) = &mut tag { + c.insert("Pos".into(), doubles([at.x, at.y, at.z])); + c.insert("Motion".into(), doubles([motion.x, motion.y, motion.z])); + c.insert( + "Rotation".into(), + Tag::List(vec![ + Tag::Float((yaw + rotation).to_bits()), + Tag::Float(pitch.to_bits()), + ]), + ); + // setPortalCooldown before the teleport, copied by restoreFrom. + c.insert("PortalCooldown".into(), Tag::Int(ENTITY_DELAY)); + } + let key = ((at.x.floor() as i32) >> 4, (at.z.floor() as i32) >> 4); + match self + .world + .loaded_entities + .iter_mut() + .find(|(k, _)| *k == key) + { + Some((_, tags)) => tags.push(tag), + None => self.world.loaded_entities.push((key, vec![tag])), + } + } + } + + // ---- persistence ---- + + fn arrivals_path(&self) -> std::path::PathBuf { + self.world_root + .join("data") + .join("horizon_portal_arrivals.dat") + } + /// The waiting entities of the open world (read once). + pub(super) fn load_portal_arrivals(&mut self) { + if self.portals.loaded || self.remote.is_some() { + return; + } + self.portals.loaded = true; + let Some(root) = horizon_client::save::read_dat(&self.arrivals_path()) else { + return; + }; + let Some(Tag::List(list)) = root.get("arrivals") else { + return; + }; + for a in list { + let int = |k: &str| match a.get(k) { + Some(Tag::Int(v)) => Some(*v), + _ => None, + }; + let float = |k: &str| match a.get(k) { + Some(Tag::Float(v)) => Some(f32::from_bits(*v)), + _ => None, + }; + let double = |k: &str| match a.get(k) { + Some(Tag::Double(v)) => Some(f64::from_bits(*v)), + _ => None, + }; + let dim = match horizon_client::save::text(a.get("dimension")).as_deref() { + Some("minecraft:the_nether") => Dim::Nether, + Some(_) => Dim::Overworld, + None => continue, + }; + let (Some(x), Some(y), Some(z), Some(tag)) = + (int("x"), int("y"), int("z"), a.get("entity")) + else { + continue; + }; + self.portals.arrivals.push(Arrival { + plan: Plan { + dim, + approximate: BlockPos::new(x, y, z), + entry_x_axis: int("x_axis").unwrap_or(1) != 0, + offset: Vec3::new( + double("right").unwrap_or(0.5), + double("up").unwrap_or(0.0), + double("forward").unwrap_or(0.0), + ), + width: float("width").unwrap_or(0.25), + height: float("height").unwrap_or(0.25), + }, + tag: tag.clone(), + }); + } + } + /// Write the waiting entities when they changed. + pub(super) fn save_portal_arrivals(&mut self) { + if !self.portals.dirty || self.remote.is_some() { + return; + } + let list = self + .portals + .arrivals + .iter() + .map(|a| { + let p = &a.plan; + Tag::compound([ + ("dimension", Tag::String(p.dim.id().into())), + ("x", Tag::Int(p.approximate.x)), + ("y", Tag::Int(p.approximate.y)), + ("z", Tag::Int(p.approximate.z)), + ("x_axis", Tag::Int(i32::from(p.entry_x_axis))), + ("right", Tag::Double(p.offset.x.to_bits())), + ("up", Tag::Double(p.offset.y.to_bits())), + ("forward", Tag::Double(p.offset.z.to_bits())), + ("width", Tag::Float(p.width.to_bits())), + ("height", Tag::Float(p.height.to_bits())), + ("entity", a.tag.clone()), + ]) + }) + .collect(); + let root = Tag::compound([("arrivals", Tag::List(list))]); + if horizon_client::save::write_dat(&self.arrivals_path(), root).is_ok() { + self.portals.dirty = false; + } + } +} diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 12cf69297..6e4b39866 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -440,7 +440,7 @@ impl Game<'_> { i } /// A mob's entity tag with the mobs riding it under `Passengers`. - fn mob_tree_nbt(&mut self, i: usize) -> Tag { + pub(super) fn mob_tree_nbt(&mut self, i: usize) -> Tag { let id = self.mobs[i].id; let uuid = self.uuid_for(id); let mut tag = entity_nbt::mob_to_nbt(&self.mobs[i], uuid, self.persist.raw.get(&id)); @@ -463,11 +463,17 @@ impl Game<'_> { } tag } + /// Forget an entity that left the world (its UUID and loaded compound). + pub(super) fn forget_entity(&mut self, id: u32) { + self.persist.uuids.remove(&id); + self.persist.raw.remove(&id); + } /// The compound an entity was loaded with (and commands have edited). pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> { self.persist.raw.get(&id) } fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) { + self.restore_portal_cooldown(id, &tag); if let Some(u) = uuid { self.persist.uuids.insert(id, u); } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 7bf040508..9fad97c5a 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -198,7 +198,7 @@ impl Game<'_> { let eye = self.eye_position(); if let Some(e) = eye { let brightness = self.eye_brightness(e); - let inside_portal = self.portal_ticks > 0; + let inside_portal = self.client_portal_effect(); self.res.screen_fx.tick(brightness, inside_portal); // LocalPlayer water vision and AtmosphericFogEnvironment rain fog. let in_water = diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 70c4ed119..81cf01e49 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -91,6 +91,7 @@ pub mod multiplayer; pub mod music; pub mod nbt_path; pub mod net; +pub mod nether_portal; pub mod options_file; pub mod options_fixes; pub mod options_horizon; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index dde0b02af..ee08f43d4 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -138,6 +138,11 @@ pub enum MotionEvent { EnterBlock { state: BlockStateId, }, + /// `NetherPortalBlock.entityInside`: the player's box swept through a + /// nether portal block. + InsidePortal { + pos: BlockPos, + }, } pub struct PlayerMotion { pub position: Vec3, @@ -962,6 +967,10 @@ impl MotionWorld<'_, '_, '_> { } "minecraft:cobweb" => self.web_inside(), "minecraft:sweet_berry_bush" => self.sweet_berry_bush_inside(state)?, + "minecraft:nether_portal" => self + .player + .events + .push(MotionEvent::InsidePortal { pos: p }), _ => {} } // ServerPlayer.onInsideBlock diff --git a/crates/horizon-client/src/nether_portal.rs b/crates/horizon-client/src/nether_portal.rs new file mode 100644 index 000000000..5f67ea3b4 --- /dev/null +++ b/crates/horizon-client/src/nether_portal.rs @@ -0,0 +1,76 @@ +//! `PortalProcessor` and an entity's portal cooldown +//! (`Entity.setAsInsidePortal` / `handlePortal`) for nether portals. +use horizon_core::position::BlockPos; + +/// `PortalProcessor` for a nether portal. +#[derive(Clone, Copy, Debug)] +pub struct Process { + pub entry: BlockPos, + pub time: i32, + pub inside: bool, +} +impl Process { + /// `processPortalTeleportation`: whether the entity goes through now. + pub fn process(&mut self, allowed: bool, transition_time: i32) -> bool { + if !self.inside { + // decayTick + self.time = (self.time - 4).max(0); + return false; + } + self.inside = false; + if !allowed { + return false; + } + let time = self.time; + self.time += 1; + time >= transition_time + } +} + +/// An entity's `portalCooldown` and `portalProcess`. +#[derive(Clone, Copy, Debug, Default)] +pub struct PortalState { + pub cooldown: i32, + pub process: Option, +} +impl PortalState { + /// `Entity.setAsInsidePortal` for a nether portal block at `pos`. + pub fn set_inside(&mut self, pos: BlockPos, delay: i32) { + if self.cooldown > 0 { + self.cooldown = delay; + return; + } + match &mut self.process { + None => { + self.process = Some(Process { + entry: pos, + time: 0, + inside: true, + }) + } + Some(p) if !p.inside => { + p.entry = pos; + p.inside = true; + } + Some(_) => {} + } + } + /// `Entity.handlePortal`: the entry block when the entity goes through + /// (its cooldown then set to `delay`). + pub fn handle(&mut self, allowed: bool, transition_time: i32, delay: i32) -> Option { + // processPortalCooldown + if self.cooldown > 0 { + self.cooldown -= 1; + } + let process = self.process.as_mut()?; + if process.process(allowed, transition_time) { + self.cooldown = delay; + return Some(process.entry); + } + // hasExpired + if process.time <= 0 { + self.process = None; + } + None + } +} diff --git a/crates/horizon-world/examples/portal_travel_fixture.rs b/crates/horizon-world/examples/portal_travel_fixture.rs new file mode 100644 index 000000000..b0843e411 --- /dev/null +++ b/crates/horizon-world/examples/portal_travel_fixture.rs @@ -0,0 +1,272 @@ +//! Rust side of tools/test_nether_portal_parity.py: replays +//! `VanillaPortalOracle` cases (an entity in a nether portal, the destination +//! level's terrain and portals) through `horizon_world::level::portal_travel` +//! and prints the same result text. +use horizon_core::{ + geometry::{Axis, Vec3}, + position::BlockPos, + random::LegacyRandom, +}; +use horizon_world::{ + level::{ + Behaviours, Dimension, LevelAccess, Ticks, + data::load_registry, + portal_travel::{ + BorderBounds, closest_portal, collision_free_position, exit_position, + largest_rectangle_around, relative_position, + }, + }, + registry::BlockStateId, +}; +use serde_json::Value; +use std::{ + collections::HashMap, + io::{BufRead, Write}, + path::Path, +}; + +struct Cells { + cells: HashMap, + air: BlockStateId, + random: LegacyRandom, + nether: bool, +} +impl LevelAccess for Cells { + fn block_state(&self, pos: BlockPos) -> BlockStateId { + self.cells.get(&pos).copied().unwrap_or(self.air) + } + fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option { + let old = self.block_state(pos); + if state == self.air { + self.cells.remove(&pos); + } else { + self.cells.insert(pos, state); + } + Some(old) + } + fn is_loaded(&self, _pos: BlockPos) -> bool { + true + } + fn min_y(&self) -> i32 { + if self.nether { 0 } else { -64 } + } + fn max_y(&self) -> i32 { + if self.nether { 256 } else { 320 } + } + fn random(&mut self) -> &mut LegacyRandom { + &mut self.random + } + fn game_time(&self) -> i64 { + 0 + } + fn dimension(&self) -> Dimension { + if self.nether { + Dimension::Nether + } else { + Dimension::Overworld + } + } +} + +fn pos(v: &Value) -> BlockPos { + BlockPos::new( + v[0].as_i64().unwrap() as i32, + v[1].as_i64().unwrap() as i32, + v[2].as_i64().unwrap() as i32, + ) +} +fn level(case: &Value, key: &str, air: BlockStateId, nether: bool) -> Cells { + let mut cells = HashMap::new(); + for c in case[key].as_array().unwrap() { + let state = BlockStateId(c[3].as_i64().unwrap() as u32); + if state != air { + cells.insert(pos(c), state); + } + } + Cells { + cells, + air, + random: LegacyRandom::new(case["seed"].as_i64().unwrap()), + nether, + } +} + +fn run(case: &Value, b: &Behaviours, air: BlockStateId, out: &mut Vec) { + let from_nether = case["from"] == "nether"; + let source = level(case, "source", air, from_nether); + let mut target = level(case, "target", air, !from_nether); + let dims = &case["entity"]["dims"]; + let (width, height) = ( + dims[0].as_f64().unwrap() as f32, + dims[1].as_f64().unwrap() as f32, + ); + out.push(format!( + "dims {:08x} {:08x}", + width.to_bits(), + height.to_bits() + )); + // Exact doubles, as bits. + let e = &case["entity"]["bits"]; + let bit = |i: usize| f64::from_bits(u64::from_str_radix(e[i].as_str().unwrap(), 16).unwrap()); + let at = Vec3::new(bit(0), bit(1), bit(2)); + // WorldBorder: centre and size, the extent clamped to +-29999984. + let border = &case["border"]; + let (cx, cz, size) = ( + border["x"].as_f64().unwrap(), + border["z"].as_f64().unwrap(), + border["size"].as_f64().unwrap(), + ); + let limit = 29_999_984.0; + let clamp = |v: f64| v.clamp(-limit, limit); + let bounds = BorderBounds { + min_x: clamp(cx - size / 2.0), + min_z: clamp(cz - size / 2.0), + max_x: clamp(cx + size / 2.0), + max_z: clamp(cz + size / 2.0), + }; + // NetherPortalBlock.getDimensionTransitionFromExit: where in its portal + // the entity stands. + let entry = pos(&case["entry"]); + let entry_state = source.block_state(entry); + let (entry_x_axis, offset) = match b.portal_axis(entry_state) { + Some(x_axis) => { + let rectangle = largest_rectangle_around( + entry, + if x_axis { Axis::X } else { Axis::Z }, + 21, + Axis::Y, + 21, + |p| source.block_state(p) == entry_state, + ); + let m = rectangle.min_corner; + out.push(format!( + "entry {},{},{} {}x{}", + m.x, m.y, m.z, rectangle.axis1_size, rectangle.axis2_size + )); + let mut offset = relative_position(rectangle, x_axis, at, width, height); + // LivingEntity, AbstractMinecart and AbstractBoat: + // resetForwardDirectionOfRelativePortalPosition. + if case["entity"]["reset_forward"].as_bool().unwrap_or(false) { + offset.z = 0.0; + } + out.push(format!( + "offset {:016x} {:016x} {:016x}", + offset.x.to_bits(), + offset.y.to_bits(), + offset.z.to_bits() + )); + (x_axis, offset) + } + None => (true, Vec3::new(0.5, 0.0, 0.0)), + }; + // NetherPortalBlock.getPortalDestination. + let scale = if from_nether { 8.0 } else { 1.0 / 8.0 }; + let approximate = bounds.clamp(at.x * scale, at.y, at.z * scale); + let portals: Vec = case["pois"].as_array().unwrap().iter().map(pos).collect(); + let (min_section, max_section) = if from_nether { (-4, 19) } else { (0, 15) }; + let mut ticks = Ticks::new(0); + out.push(format!( + "approximate {},{},{}", + approximate.x, approximate.y, approximate.z + )); + let found = closest_portal( + &portals, + approximate, + !from_nether, + &bounds, + min_section, + max_section, + ); + out.push(match found { + Some(p) => format!("found {},{},{}", p.x, p.y, p.z), + None => "found none".into(), + }); + let exit = match found { + Some(found) => { + let state = target.block_state(found); + let x_axis = b.portal_axis(state).unwrap_or(true); + Some(largest_rectangle_around( + found, + if x_axis { Axis::X } else { Axis::Z }, + 21, + Axis::Y, + 21, + |p| target.block_state(p) == state, + )) + } + None => { + let logical = if from_nether { 384 } else { 128 }; + b.create_portal( + &mut target, + &mut ticks, + approximate, + entry_x_axis, + &bounds, + logical, + ) + } + }; + let mut changed: Vec = target + .cells + .keys() + .copied() + .chain( + level(case, "target", air, !from_nether) + .cells + .keys() + .copied(), + ) + .collect(); + changed.sort_by_key(|p| (p.x, p.y, p.z)); + changed.dedup(); + let before = level(case, "target", air, !from_nether); + for p in changed { + let now = target.block_state(p); + if before.block_state(p) != now { + out.push(format!("set {},{},{} {}", p.x, p.y, p.z, now.0)); + } + } + let Some(exit) = exit else { + out.push("dest none".into()); + return; + }; + let exit_x_axis = b + .portal_axis(target.block_state(exit.min_corner)) + .unwrap_or(true); + let (bottom, rotation) = exit_position(exit, exit_x_axis, entry_x_axis, offset, width, height); + let free = collision_free_position(bottom, width, height, &bounds, |p| { + b.collision_shape(target.block_state(p)) + .map(|s| s.moved(Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)))) + }); + out.push(format!( + "dest {:016x} {:016x} {:016x} {rotation:?}", + free.x.to_bits(), + free.y.to_bits(), + free.z.to_bits() + )); +} + +fn main() -> Result<(), Box> { + let mut args = std::env::args().skip(1); + let resources = args.next().expect("resource directory"); + let cases = args.next().expect("case file"); + let output = args.next().expect("output file"); + let resources = Path::new(&resources); + let registry = load_registry(resources)?; + let behaviours = Behaviours::load(®istry, resources)?; + let air = registry.default_state("minecraft:air").unwrap(); + let mut out = std::io::BufWriter::new(std::fs::File::create(output)?); + for (index, line) in std::io::BufReader::new(std::fs::File::open(cases)?) + .lines() + .enumerate() + { + let case: Value = serde_json::from_str(&line?)?; + let mut lines = Vec::new(); + run(&case, &behaviours, air, &mut lines); + writeln!(out, "case {index}")?; + for l in lines { + writeln!(out, "{l}")?; + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index f04c65941..05b531c76 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -112,6 +112,7 @@ mod interact; pub mod pistons; mod place; mod portal; +pub mod portal_travel; mod query; mod rails; mod redstone; diff --git a/crates/horizon-world/src/level/portal_travel.rs b/crates/horizon-world/src/level/portal_travel.rs new file mode 100644 index 000000000..3bd8a11f4 --- /dev/null +++ b/crates/horizon-world/src/level/portal_travel.rs @@ -0,0 +1,628 @@ +//! Nether portal travel: `PortalForcer` (finding and building exit portals), +//! `BlockUtil.getLargestRectangleAround`, `PortalShape.getRelativePosition` +//! and `NetherPortalBlock.createDimensionTransition`. +use super::{Behaviours, LevelAccess, Sim, Ticks}; +use crate::fluid::FluidKind; +use crate::{ + java_hash_map::{JavaHashMap, JavaKey}, + registry::BlockStateId, +}; +use horizon_core::{ + geometry::{Aabb, Axis, Direction, ShapeOp, Vec3, VoxelShape}, + position::BlockPos, +}; +use std::cmp::Ordering; + +/// `BlockUtil.FoundRectangle`: the low corner and the sizes along the two axes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FoundRectangle { + pub min_corner: BlockPos, + pub axis1_size: i32, + pub axis2_size: i32, +} + +/// The world border's extent (`getMinX` .. `getMaxX`, `getMinZ` .. `getMaxZ`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BorderBounds { + pub min_x: f64, + pub min_z: f64, + pub max_x: f64, + pub max_z: f64, +} +impl BorderBounds { + /// `WorldBorder.isWithinBounds(x, z)`. + pub fn contains(&self, x: f64, z: f64) -> bool { + x >= self.min_x && x < self.max_x && z >= self.min_z && z < self.max_z + } + /// `WorldBorder.isWithinBounds(BlockPos)`. + pub fn contains_block(&self, pos: BlockPos) -> bool { + self.contains(f64::from(pos.x), f64::from(pos.z)) + } + /// `WorldBorder.clampToBounds(x, y, z)`. + pub fn clamp(&self, x: f64, y: f64, z: f64) -> BlockPos { + let margin = f64::from(1.0e-5_f32); + let clamp = |v: f64, lo: f64, hi: f64| if v < lo { lo } else { v.min(hi) }; + BlockPos::new( + clamp(x, self.min_x, self.max_x - margin).floor() as i32, + y.floor() as i32, + clamp(z, self.min_z, self.max_z - margin).floor() as i32, + ) + } +} + +fn step(pos: BlockPos, direction: Direction, n: i32) -> BlockPos { + let [dx, dy, dz] = direction.normal(); + pos.offset(dx * n, dy * n, dz * n) +} +fn negative(axis: Axis) -> Direction { + match axis { + Axis::X => Direction::West, + Axis::Y => Direction::Down, + Axis::Z => Direction::North, + } +} +fn component(pos: BlockPos, axis: Axis) -> i32 { + match axis { + Axis::X => pos.x, + Axis::Y => pos.y, + Axis::Z => pos.z, + } +} +/// `Direction.getClockWise` for the horizontal directions. +fn clockwise(direction: Direction) -> Direction { + match direction { + Direction::North => Direction::East, + Direction::East => Direction::South, + Direction::South => Direction::West, + Direction::West => Direction::North, + other => other, + } +} + +/// `BlockUtil.getLimit`: how many steps from `start` along `direction` pass `test`. +fn limit( + test: &mut impl FnMut(BlockPos) -> bool, + start: BlockPos, + direction: Direction, + limit: i32, +) -> i32 { + let mut max = 0; + let mut pos = start; + while max < limit { + pos = step(pos, direction, 1); + if !test(pos) { + break; + } + max += 1; + } + max +} + +/// `BlockUtil.getMaxRectangleLocation`: the widest-area run of `columns` +/// (start, end inclusive) and its height. +fn max_rectangle_location(columns: &[i32]) -> (i32, i32, i32) { + let (mut max_start, mut max_end, mut max_height) = (0usize, 0usize, 0i32); + let mut stack: Vec = vec![0]; + for column in 1..=columns.len() { + let height = if column == columns.len() { + 0 + } else { + columns[column] + }; + while let Some(&top) = stack.last() { + let stack_height = columns[top]; + if height >= stack_height { + stack.push(column); + break; + } + stack.pop(); + let start = stack.last().map_or(0, |t| t + 1); + if i64::from(stack_height) * (column - start) as i64 + > i64::from(max_height) * (max_end - max_start) as i64 + { + max_end = column; + max_start = start; + max_height = stack_height; + } + } + if stack.is_empty() { + stack.push(column); + } + } + (max_start as i32, max_end as i32 - 1, max_height) +} + +/// `BlockUtil.getLargestRectangleAround`: the largest rectangle of positions +/// passing `test` in the plane of `axis1` and `axis2` that contains `center`. +pub fn largest_rectangle_around( + center: BlockPos, + axis1: Axis, + limit1: i32, + axis2: Axis, + limit2: i32, + mut test: impl FnMut(BlockPos) -> bool, +) -> FoundRectangle { + let negative1 = negative(axis1); + let positive1 = negative1.opposite(); + let negative2 = negative(axis2); + let positive2 = negative2.opposite(); + let negative_delta1 = limit(&mut test, center, negative1, limit1); + let positive_delta1 = limit(&mut test, center, positive1, limit1); + let center_index1 = negative_delta1 as usize; + let mut bounds = vec![(0, 0); center_index1 + 1 + positive_delta1 as usize]; + bounds[center_index1] = ( + limit(&mut test, center, negative2, limit2), + limit(&mut test, center, positive2, limit2), + ); + let center_index2 = bounds[center_index1].0; + for i in 1..=negative_delta1 as usize { + let last = bounds[center_index1 - (i - 1)]; + let at = step(center, negative1, i as i32); + bounds[center_index1 - i] = ( + limit(&mut test, at, negative2, last.0), + limit(&mut test, at, positive2, last.1), + ); + } + for i in 1..=positive_delta1 as usize { + let last = bounds[center_index1 + i - 1]; + let at = step(center, positive1, i as i32); + bounds[center_index1 + i] = ( + limit(&mut test, at, negative2, last.0), + limit(&mut test, at, positive2, last.1), + ); + } + let (mut min_axis1, mut min_axis2, mut size_axis1, mut size_axis2) = (0, 0, 0, 0); + let mut columns = vec![0; bounds.len()]; + for i2 in (0..=center_index2).rev() { + for (i1, b) in bounds.iter().enumerate() { + let min2 = center_index2 - b.0; + let max2 = center_index2 + b.1; + columns[i1] = if i2 >= min2 && i2 <= max2 { + max2 + 1 - i2 + } else { + 0 + }; + } + let (start, end, height) = max_rectangle_location(&columns); + let new_size1 = 1 + end - start; + if new_size1 * height > size_axis1 * size_axis2 { + min_axis1 = start; + min_axis2 = i2; + size_axis1 = new_size1; + size_axis2 = height; + } + } + let corner = step( + center, + negative1.opposite(), + min_axis1 - center_index1 as i32, + ); + let corner = step(corner, negative2.opposite(), min_axis2 - center_index2); + FoundRectangle { + min_corner: corner, + axis1_size: size_axis1, + axis2_size: size_axis2, + } +} + +/// `PortalShape.getRelativePosition`: where in the portal rectangle an entity +/// of `width` by `height` at `position` stands (right and up as fractions, +/// forward in blocks; living entities, minecarts and boats then drop the +/// forward part, `LivingEntity.resetForwardDirectionOfRelativePortalPosition`). +pub fn relative_position( + rectangle: FoundRectangle, + x_axis: bool, + position: Vec3, + width: f32, + height: f32, +) -> Vec3 { + let axis = if x_axis { Axis::X } else { Axis::Z }; + let room_width = f64::from(rectangle.axis1_size) - f64::from(width); + let room_height = f64::from(rectangle.axis2_size) - f64::from(height); + let bottom = rectangle.min_corner; + let clamp = |v: f64| if v < 0.0 { 0.0 } else { v.min(1.0) }; + let right = if room_width > 0.0 { + let start = f64::from(component(bottom, axis)) + f64::from(width) / 2.0; + clamp((position.component(axis) - start) / room_width) + } else { + 0.5 + }; + let up = if room_height > 0.0 { + clamp((position.y - f64::from(bottom.y)) / room_height) + } else { + 0.0 + }; + let forward_axis = if x_axis { Axis::Z } else { Axis::X }; + let forward = + position.component(forward_axis) - (f64::from(component(bottom, forward_axis)) + 0.5); + Vec3::new(right, up, forward) +} + +/// `NetherPortalBlock.createDimensionTransition` before +/// `PortalShape.findCollisionFreePosition`: the bottom centre of the entity in +/// the exit portal and the yaw it turns by (0 or 90). +pub fn exit_position( + exit: FoundRectangle, + exit_x_axis: bool, + entry_x_axis: bool, + offset: Vec3, + width: f32, + height: f32, +) -> (Vec3, f32) { + let rotation = if entry_x_axis == exit_x_axis { + 0.0 + } else { + 90.0 + }; + let right = f64::from(width) / 2.0 + (f64::from(exit.axis1_size) - f64::from(width)) * offset.x; + let up = (f64::from(exit.axis2_size) - f64::from(height)) * offset.y; + let forward = 0.5 + offset.z; + let b = exit.min_corner; + let target = Vec3::new( + f64::from(b.x) + if exit_x_axis { right } else { forward }, + f64::from(b.y) + up, + f64::from(b.z) + if exit_x_axis { forward } else { right }, + ); + (target, rotation) +} + +impl BorderBounds { + /// `WorldBorder.isWithinBounds(AABB)`: both corners, the far one pulled + /// in by 1.0E-5F. + pub fn contains_box(&self, b: Aabb) -> bool { + let margin = f64::from(1.0e-5_f32); + self.contains(b.min(Axis::X), b.min(Axis::Z)) + && self.contains(b.max(Axis::X) - margin, b.max(Axis::Z) - margin) + } +} + +/// `CollisionGetter.findFreePosition` without an entity's collision context: +/// within `allowed`, the point nearest `preferred` where a box of the size +/// centred there meets no block collision inside the border. `shape(pos)` +/// is the block's collision shape there, in world coordinates. +pub fn find_free_position( + allowed: Aabb, + preferred: Vec3, + size: Vec3, + border: &BorderBounds, + mut shape: impl FnMut(BlockPos) -> Option, +) -> Option { + let allowed_shape = VoxelShape::from_box(allowed).ok()?; + if allowed_shape.is_empty() { + return None; + } + let search = allowed_shape.bounds()?.inflate(size); + let half = size.scale(0.5); + let mut expanded = VoxelShape::empty(); + // BlockCollisions over the search area: every block whose shape meets it. + let lo = |v: f64| (v - 1.0e-7).floor() as i32 - 1; + let hi = |v: f64| (v + 1.0e-7).floor() as i32 + 1; + for z in lo(search.min(Axis::Z))..=hi(search.max(Axis::Z)) { + for y in lo(search.min(Axis::Y))..=hi(search.max(Axis::Y)) { + for x in lo(search.min(Axis::X))..=hi(search.max(Axis::X)) { + let Some(block) = shape(BlockPos::new(x, y, z)) else { + continue; + }; + if block.is_empty() + || !block.boxes().iter().any(|b| b.intersects(search)) + || !block.bounds().is_some_and(|b| border.contains_box(b)) + { + continue; + } + for b in block.boxes() { + let grown = VoxelShape::from_box(b.inflate(half)).ok()?; + expanded = expanded.join(&grown, ShapeOp::OR).ok()?; + } + } + } + } + let free = allowed_shape.join(&expanded, ShapeOp::ONLY_FIRST).ok()?; + free.closest_point(preferred) +} + +/// `PortalShape.findCollisionFreePosition`: `bottom_center` moved to the +/// nearest spot within its column of the entity's width (and a block up) +/// where it fits; entities over 4 blocks stay put. +pub fn collision_free_position( + bottom_center: Vec3, + width: f32, + height: f32, + border: &BorderBounds, + shape: impl FnMut(BlockPos) -> Option, +) -> Vec3 { + if width > 4.0 || height > 4.0 { + return bottom_center; + } + let half_height = f64::from(height) / 2.0; + let center = bottom_center.add_vector(Vec3::new(0.0, half_height, 0.0)); + let w = f64::from(width); + let allowed = Aabb::of_size(center, Vec3::new(w, 0.0, w)) + .expand_towards(Vec3::new(0.0, 1.0, 0.0)) + .inflate(Vec3::new(1.0e-6, 1.0e-6, 1.0e-6)); + find_free_position( + allowed, + center, + Vec3::new(w, f64::from(height), w), + border, + shape, + ) + .map_or(bottom_center, |p| { + p.subtract(Vec3::new(0.0, half_height, 0.0)) + }) +} + +/// A portal block position as a `PoiRecord` in a `PoiSection`'s hash set. +#[derive(Clone, Copy, PartialEq, Eq)] +struct Record(BlockPos); +impl JavaKey for Record { + /// `Vec3i.hashCode`. + fn java_hash(&self) -> i32 { + let p = self.0; + p.y.wrapping_add(p.z.wrapping_mul(31)) + .wrapping_mul(31) + .wrapping_add(p.x) + } + fn tie_break(&self, other: &Self) -> Ordering { + (self.0.y, self.0.z, self.0.x) + .cmp(&(other.0.y, other.0.z, other.0.x)) + .then(Ordering::Less) + } +} + +/// `PortalForcer.findClosestPortalPosition` over the nether portal blocks +/// `portals` (the points of interest, in the order their sections hold +/// them): within 16 blocks of `approximate` going to the Nether, 128 out of +/// it, inside the border, nearest first, then lowest. +pub fn closest_portal( + portals: &[BlockPos], + approximate: BlockPos, + to_nether: bool, + border: &BorderBounds, + min_section: i32, + max_section: i32, +) -> Option { + let radius: i32 = if to_nether { 16 } else { 128 }; + // PoiManager.getInSquare: the chunks of ChunkPos.rangeClosed (x fastest), + // each section from the bottom, each section's records in hash set order. + let chunk_radius = radius.div_euclid(16) + 1; + let (cx, cz) = (approximate.x >> 4, approximate.z >> 4); + let mut sections: std::collections::HashMap<(i32, i32, i32), JavaHashMap> = + std::collections::HashMap::new(); + for &p in portals { + sections + .entry((p.x >> 4, p.y >> 4, p.z >> 4)) + .or_default() + .put(Record(p), ()); + } + let mut best: Option<(f64, BlockPos)> = None; + for z in cz - chunk_radius..=cz + chunk_radius { + for x in cx - chunk_radius..=cx + chunk_radius { + for y in min_section..=max_section { + let Some(set) = sections.get(&(x, y, z)) else { + continue; + }; + for (record, _) in set.entries() { + let p = record.0; + if (p.x - approximate.x).abs() > radius + || (p.z - approximate.z).abs() > radius + || !border.contains_block(p) + { + continue; + } + let (dx, dy, dz) = ( + f64::from(p.x) - f64::from(approximate.x), + f64::from(p.y) - f64::from(approximate.y), + f64::from(p.z) - f64::from(approximate.z), + ); + let d = dx * dx + dy * dy + dz * dz; + if best.is_none_or(|(bd, bp)| d < bd || (d == bd && p.y < bp.y)) { + best = Some((d, p)); + } + } + } + } + } + best.map(|(_, p)| p) +} + +/// `BlockPos.spiralAround(center, radius, first, second)`. +fn spiral_around( + center: BlockPos, + radius: i32, + first: Direction, + second: Direction, +) -> Vec { + let directions = [first, second, first.opposite(), second.opposite()]; + let mut out = Vec::new(); + let mut last = step(center, second, 1); + let legs = 4 * radius; + let (mut leg, mut leg_size, mut leg_index) = (-1i32, 0, 0); + loop { + let cursor = step(last, directions[((leg + 4) % 4) as usize], 1); + last = cursor; + if leg_index >= leg_size { + if leg >= legs { + return out; + } + leg += 1; + leg_index = 0; + leg_size = leg / 2 + 1; + } + leg_index += 1; + out.push(cursor); + } +} + +impl Sim<'_, L> { + /// `PortalForcer.canPortalReplaceBlock`. + fn portal_can_replace(&self, pos: BlockPos) -> bool { + let state = self.state(pos); + self.b.is_replaceable(state) && self.b.fluid(state).kind() == FluidKind::Empty + } + /// `PortalForcer.canHostFrame`. + fn can_host_frame(&self, origin: BlockPos, direction: Direction, offset: i32) -> bool { + let side = clockwise(direction); + for width in -1..3 { + for height in -1..4 { + let at = step(step(origin, direction, width), side, offset).offset(0, height, 0); + if height < 0 && !self.b.is_solid(self.state(at)) { + return false; + } + if height >= 0 && !self.portal_can_replace(at) { + return false; + } + } + } + true + } + /// `PortalForcer.createPortal`: a 2 by 3 portal in an obsidian frame at the + /// nearest column around `origin` with room for it (on a platform it + /// carves out when none has), facing `x_axis`. + pub fn create_portal( + &mut self, + origin: BlockPos, + x_axis: bool, + border: &BorderBounds, + logical_height: i32, + ) -> Option { + let direction = if x_axis { + Direction::East + } else { + Direction::South + }; + let (min_y, max_y) = (self.level.min_y(), self.level.max_y() - 1); + let max_placeable = max_y.min(min_y + logical_height - 1); + let distance = |a: BlockPos, b: BlockPos| { + let (dx, dy, dz) = ( + f64::from(a.x) - f64::from(b.x), + f64::from(a.y) - f64::from(b.y), + f64::from(a.z) - f64::from(b.z), + ); + dx * dx + dy * dy + dz * dz + }; + let mut full: Option<(f64, BlockPos)> = None; + let mut partial: Option<(f64, BlockPos)> = None; + for column in spiral_around(origin, 16, Direction::East, Direction::South) { + let top = self.b.motion_blocking_top(&*self.level, column).y; + let height = max_placeable.min(top); + if !border.contains_block(column) || !border.contains_block(step(column, direction, 1)) + { + continue; + } + let mut y = height; + while y >= min_y { + let at = BlockPos::new(column.x, y, column.z); + if self.portal_can_replace(at) { + let first_empty = y; + while y > min_y + && self.portal_can_replace(BlockPos::new(column.x, y - 1, column.z)) + { + y -= 1; + } + if y + 4 <= max_placeable { + let delta = first_empty - y; + if delta <= 0 || delta >= 3 { + let at = BlockPos::new(column.x, y, column.z); + if self.can_host_frame(at, direction, 0) { + let d = distance(origin, at); + if self.can_host_frame(at, direction, -1) + && self.can_host_frame(at, direction, 1) + && full.is_none_or(|(fd, _)| fd > d) + { + full = Some((d, at)); + } + if full.is_none() && partial.is_none_or(|(pd, _)| pd > d) { + partial = Some((d, at)); + } + } + } + } + } + y -= 1; + } + } + let b = self.b; + let obsidian = b.default_of(b.named.obsidian); + let spot = match full.or(partial) { + Some((_, spot)) => spot, + None => { + let min_start = (min_y + 1).max(70); + let max_start = max_placeable - 9; + if max_start < min_start { + return None; + } + let [sx, _, sz] = direction.normal(); + let y = origin.y.clamp(min_start, max_start); + let spot = border.clamp( + f64::from(origin.x - sx), + f64::from(y), + f64::from(origin.z - sz), + ); + let side = clockwise(direction); + let air = b.default_of(b.named.air); + for side_offset in -1..2 { + for width in 0..2 { + for height in -1..3 { + let at = step(step(spot, direction, width), side, side_offset) + .offset(0, height, 0); + self.set_block(at, if height < 0 { obsidian } else { air }, 3); + } + } + } + spot + } + }; + for width in -1..3 { + for height in -1..4 { + if width == -1 || width == 2 || height == -1 || height == 3 { + self.set_block( + step(spot, direction, width).offset(0, height, 0), + obsidian, + 3, + ); + } + } + } + let base = b.default_of(b.named.nether_portal); + let portal = b + .table + .with_text(base, b.props.axis, if x_axis { "x" } else { "z" }) + .unwrap_or(base); + for width in 0..2 { + for height in 0..3 { + self.set_block( + step(spot, direction, width).offset(0, height, 0), + portal, + 18, + ); + } + } + Some(FoundRectangle { + min_corner: spot, + axis1_size: 2, + axis2_size: 3, + }) + } +} + +impl Behaviours { + /// `PortalForcer.createPortal` on `level` (see `Sim::create_portal`). + pub fn create_portal( + &self, + level: &mut L, + ticks: &mut Ticks, + origin: BlockPos, + x_axis: bool, + border: &BorderBounds, + logical_height: i32, + ) -> Option { + self.sim(level, ticks) + .create_portal(origin, x_axis, border, logical_height) + } + /// The axis of a nether portal state: Some(true) for X, Some(false) for + /// Z, None for other blocks. + pub fn portal_axis(&self, state: BlockStateId) -> Option { + self.is_block(state, self.named.nether_portal) + .then(|| self.table.text(state, self.props.axis) == "x") + } +} 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 8d9cde712..ce6b8cdc7 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -71,6 +71,7 @@ public final class VanillaBlockUpdateOracle { if (old == state) { return null; } + world.columns = null; if (state == AIR) { world.cells.remove(pos); } else { @@ -189,8 +190,29 @@ public final class VanillaBlockUpdateOracle { @Override public boolean hasChunk(int x, int z) { return true; } @Override public boolean isClientSide() { return false; } @Override public RandomSource getRandom() { return rng; } - @Override public int getMinY() { return -64; } - @Override public int getHeight() { return 384; } + // Another dimension, border and points of interest (the portal oracle); + // the overworld and an unbounded border when unset. + net.minecraft.world.level.dimension.DimensionType type; + net.minecraft.resources.ResourceKey dimensionKey; + net.minecraft.world.level.border.WorldBorder border; + net.minecraft.world.entity.ai.village.poi.PoiManager poi; + @Override public int getMinY() { return type == null ? -64 : type.minY(); } + @Override public int getHeight() { return type == null ? 384 : type.height(); } + @Override public net.minecraft.world.entity.ai.village.poi.PoiManager getPoiManager() { return poi != null ? poi : super.getPoiManager(); } + /** Level.getHeight from the cells (only for another dimension's level). */ + Map> columns; + @Override public int getHeight(net.minecraft.world.level.levelgen.Heightmap.Types kind, int x, int z) { + if (type == null) return super.getHeight(kind, x, z); + if (columns == null) { + columns = new HashMap<>(); + for (BlockPos c : cells.keySet()) columns.computeIfAbsent(BlockPos.asLong(c.getX(), 0, c.getZ()), k -> new ArrayList<>()).add(c); + } + int top = getMinY() - 1; + for (BlockPos c : columns.getOrDefault(BlockPos.asLong(x, 0, z), List.of())) { + if (c.getY() > top && kind.isOpaque().test(getBlockState(c))) top = c.getY(); + } + return top + 1; + } @Override public long getGameTime() { return time; } @Override public long nextSubTickCount() { return subTick++; } @Override public LevelTicks getBlockTicks() { return blockTicks; } @@ -202,7 +224,7 @@ public final class VanillaBlockUpdateOracle { @Override public GameRules getGameRules() { return rules; } @Override public net.minecraft.server.MinecraftServer getServer() { return server; } @Override public net.minecraft.world.item.crafting.RecipeManager recipeAccess() { return Server.recipes; } - @Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return new net.minecraft.world.level.border.WorldBorder(); } + @Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return border != null ? border : new net.minecraft.world.level.border.WorldBorder(); } @Override public int getSeaLevel() { return 63; } @Override public int getBrightness(net.minecraft.world.level.LightLayer layer, BlockPos p) { return layer == net.minecraft.world.level.LightLayer.SKY ? skyLight : blockLight; } @Override public int getRawBrightness(BlockPos p, int darkening) { return Math.max(skyLight - darkening, blockLight); } @@ -328,9 +350,9 @@ public final class VanillaBlockUpdateOracle { } return attributes; } - @Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return OVERWORLD_TYPE; } + @Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return type != null ? type : OVERWORLD_TYPE; } /** The overworld (fire in an obsidian frame lights a portal here). */ - @Override public net.minecraft.resources.ResourceKey dimension() { return net.minecraft.world.level.Level.OVERWORLD; } + @Override public net.minecraft.resources.ResourceKey dimension() { return dimensionKey != null ? dimensionKey : net.minecraft.world.level.Level.OVERWORLD; } @Override public long getOverworldClockTime() { return DAY.totalTicks(); } @Override public float getMoonBrightness(BlockPos p) { return net.minecraft.world.level.dimension.DimensionType.MOON_BRIGHTNESS_PER_PHASE[environmentAttributes().getValue(net.minecraft.world.attribute.EnvironmentAttributes.MOON_PHASE, p).index()]; @@ -408,6 +430,10 @@ public final class VanillaBlockUpdateOracle { /** The overworld dimension type from the vanilla data pack (its infiniburn tag, attributes and timelines). */ static net.minecraft.world.level.dimension.DimensionType loadOverworld() { + return loadDimensionType(net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD); + } + + static net.minecraft.world.level.dimension.DimensionType loadDimensionType(net.minecraft.resources.ResourceKey key) { var repo = net.minecraft.server.packs.repository.ServerPacksSource.createVanillaTrustedRepository(); repo.reload(); repo.setSelected(List.of("vanilla")); @@ -417,7 +443,7 @@ public final class VanillaBlockUpdateOracle { var context = net.minecraft.tags.TagLoader.buildUpdatedLookups(layers.getAccessForLoading(net.minecraft.server.RegistryLayer.WORLD), staticTags); var world = net.minecraft.resources.RegistryDataLoader.load(resources, context, net.minecraft.resources.RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); staticTags.forEach(net.minecraft.core.Registry.PendingTags::apply); - return world.lookupOrThrow(net.minecraft.core.registries.Registries.DIMENSION_TYPE).getOrThrow(net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD).value(); + return world.lookupOrThrow(net.minecraft.core.registries.Registries.DIMENSION_TYPE).getOrThrow(key).value(); } static final class Loot extends net.minecraft.server.ReloadableServerRegistries.Holder { @@ -449,6 +475,9 @@ public final class VanillaBlockUpdateOracle { @Override public net.minecraft.world.item.crafting.RecipeManager getRecipeManager() { return recipes; } @Override public net.minecraft.server.ReloadableServerRegistries.Holder reloadableRegistries() { return loot; } @Override protected boolean initServer() { return false; } + /** The levels by dimension (the portal oracle's two). */ + Map, net.minecraft.server.level.ServerLevel> levels; + @Override public net.minecraft.server.level.ServerLevel getLevel(net.minecraft.resources.ResourceKey key) { return levels == null ? null : levels.get(key); } @Override public int getMaxPlayers() { return 0; } @Override public net.minecraft.server.permissions.LevelBasedPermissionSet operatorUserPermissions() { return null; } @Override public net.minecraft.server.permissions.PermissionSet getFunctionCompilationPermissions() { return null; } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPortalOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPortalOracle.java new file mode 100644 index 000000000..4f6b43973 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPortalOracle.java @@ -0,0 +1,144 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.core.SectionPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.ai.village.poi.PoiManager; +import net.minecraft.world.entity.ai.village.poi.PoiSection; +import net.minecraft.world.entity.ai.village.poi.PoiTypes; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.NetherPortalBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; + +/** + * Nether portal travel, one entity per case: `NetherPortalBlock.getPortalDestination` + * for an entity standing in a portal of one headless level (the block update + * oracle's), going to another (the Nether from the overworld or back), whose + * points of interest are the case's portal blocks in the case's order. It runs + * `PortalForcer.findClosestPortalPosition` and, when nothing is found, + * `createPortal`, `BlockUtil.getLargestRectangleAround`, + * `PortalShape.getRelativePosition` and `findCollisionFreePosition`. Printed: + * the entity's size, the exit portal found (or "created"), the blocks the + * destination changed and the arrival position (bits) and yaw. + */ +public final class VanillaPortalOracle { + /** The points of interest of the destination: the case's portal blocks. */ + static final class Poi extends PoiManager { + Map sections; + Poi() { + super(null, null, null, false, null, null, null); + } + @Override protected Optional getOrLoad(long key) { return Optional.ofNullable(sections.get(key)); } + @Override public void ensureLoadedAndValid(net.minecraft.world.level.LevelReader reader, BlockPos center, int radius) { } + } + + static net.minecraft.world.level.dimension.DimensionType OVERWORLD, NETHER; + + public static void main(String[] args) throws Exception { + ParityData.init(); + VanillaBlockUpdateOracle.AIR = Blocks.AIR.defaultBlockState(); + VanillaLevelShapeOracle.bindFluidTags(Path.of(args[0]).resolve("data/minecraft/tags/fluid")); + OVERWORLD = VanillaBlockUpdateOracle.OVERWORLD_TYPE = VanillaBlockUpdateOracle.loadOverworld(); + NETHER = VanillaBlockUpdateOracle.loadDimensionType(BuiltinDimensionTypes.NETHER); + var allocator = Class.forName("sun.misc.Unsafe"); + var field = allocator.getDeclaredField("theUnsafe"); + field.setAccessible(true); + VanillaBlockUpdateOracle.unsafe = field.get(null); + VanillaBlockUpdateOracle.allocate = allocator.getMethod("allocateInstance", Class.class); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) { + int index = 0; + for (var line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + out.print("case " + index++ + "\n"); + try { + for (String s : run(f)) out.print(s + "\n"); + } catch (Throwable e) { + Throwable c = e; + while (c.getCause() != null) c = c.getCause(); + if (System.getenv("ORACLE_TRACE") != null) c.printStackTrace(); + StackTraceElement[] st = c.getStackTrace(); + out.print("error " + c.getClass().getSimpleName() + " " + (st.length > 0 ? st[0].toString() : "") + " " + c.getMessage() + "\n"); + } + } + } + } + + static VanillaBlockUpdateOracle.World level(JsonObject f, String cells, boolean nether) throws Exception { + var copy = new JsonObject(); + copy.add("cells", f.get(cells)); + copy.add("seed", f.get("seed")); + var w = VanillaBlockUpdateOracle.build(copy); + w.type = nether ? NETHER : OVERWORLD; + w.dimensionKey = nether ? Level.NETHER : Level.OVERWORLD; + return w; + } + + static List run(JsonObject f) throws Exception { + boolean fromNether = f.get("from").getAsString().equals("nether"); + var source = level(f, "source", fromNether); + var target = level(f, "target", !fromNether); + var levels = new HashMap, net.minecraft.server.level.ServerLevel>(); + levels.put(source.dimension(), source); + levels.put(target.dimension(), target); + source.server.levels = levels; + target.server = source.server; + var border = new net.minecraft.world.level.border.WorldBorder(); + var b = f.getAsJsonObject("border"); + border.setCenter(b.get("x").getAsDouble(), b.get("z").getAsDouble()); + border.setSize(b.get("size").getAsDouble()); + target.border = border; + var poi = (Poi) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Poi.class); + poi.sections = new HashMap<>(); + VanillaBlockUpdateOracle.set(net.minecraft.world.level.chunk.storage.SectionStorage.class, poi, "levelHeightAccessor", target); + var portalType = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getOrThrow(PoiTypes.NETHER_PORTAL); + for (var p : f.getAsJsonArray("pois")) { + BlockPos at = VanillaBlockUpdateOracle.readPos(p.getAsJsonArray()); + poi.sections.computeIfAbsent(SectionPos.asLong(at), k -> new PoiSection(() -> { })).add(at, portalType); + } + target.poi = poi; + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerLevel.class, target, "portalForcer", new net.minecraft.world.level.portal.PortalForcer(target)); + var e = f.getAsJsonObject("entity"); + Entity entity = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(e.get("type").getAsString())).create(source, EntitySpawnReason.LOAD); + // Exact doubles, as bits. + var at = e.getAsJsonArray("bits"); + java.util.function.IntToDoubleFunction bit = i -> Double.longBitsToDouble(Long.parseUnsignedLong(at.get(i).getAsString(), 16)); + entity.setPos(bit.applyAsDouble(0), bit.applyAsDouble(1), bit.applyAsDouble(2)); + List out = new ArrayList<>(); + var dimensions = entity.getDimensions(entity.getPose()); + out.add(String.format("dims %08x %08x", Float.floatToIntBits(dimensions.width()), Float.floatToIntBits(dimensions.height()))); + Map before = new HashMap<>(target.cells); + BlockPos entry = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("entry")); + // The steps getPortalDestination takes, for the report. + BlockState entryState = source.getBlockState(entry); + if (entryState.hasProperty(NetherPortalBlock.AXIS)) { + var axis = entryState.getValue(NetherPortalBlock.AXIS); + var area = net.minecraft.util.BlockUtil.getLargestRectangleAround(entry, axis, 21, net.minecraft.core.Direction.Axis.Y, 21, q -> source.getBlockState(q) == entryState); + out.add("entry " + VanillaBlockUpdateOracle.pos(area.minCorner) + " " + area.axis1Size + "x" + area.axis2Size); + var offset = entity.getRelativePortalPosition(axis, area); + out.add(String.format("offset %016x %016x %016x", Double.doubleToLongBits(offset.x), Double.doubleToLongBits(offset.y), Double.doubleToLongBits(offset.z))); + } + double scale = net.minecraft.world.level.dimension.DimensionType.getTeleportationScale(source.dimensionType(), target.dimensionType()); + BlockPos approximate = border.clampToBounds(entity.getX() * scale, entity.getY(), entity.getZ() * scale); + out.add("approximate " + VanillaBlockUpdateOracle.pos(approximate)); + out.add("found " + target.getPortalForcer().findClosestPortalPosition(approximate, !fromNether, border).map(VanillaBlockUpdateOracle::pos).orElse("none")); + var transition = ((NetherPortalBlock) Blocks.NETHER_PORTAL).getPortalDestination(source, entity, entry); + out.addAll(VanillaBlockUpdateOracle.summary(target, before)); + if (transition == null) { + out.add("dest none"); + } else { + var p = transition.position(); + out.add(String.format("dest %016x %016x %016x %s", Double.doubleToLongBits(p.x), Double.doubleToLongBits(p.y), Double.doubleToLongBits(p.z), + Float.toString(transition.yRot()))); + } + return out; + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java index 4ff64b7da..49dc7753c 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java @@ -227,6 +227,21 @@ public final class VanillaSceneMotionOracle { @Override public Vec3 getKnownMovement(){return tickStart==null?Vec3.ZERO:position().subtract(tickStart);} @Override protected void applyInput(){if(!preparedInput)super.applyInput();} void peaceful(){tickRegeneration();} + // Entity.handlePortal without the destination (none: one level here), + // remembering the entry of a portal it would go through. + String travel; + // The creative delay applies with invulnerable abilities, set only for + // the transition time (the scene's food code runs without abilities). + void portalTick(boolean creative){ + processPortalCooldown(); + if(portalProcess!=null){ + var entry=portalProcess.getEntryPosition(); + boolean was=getAbilities().invulnerable;getAbilities().invulnerable=creative; + boolean through;try{through=portalProcess.processPortalTeleportation((net.minecraft.server.level.ServerLevel)sceneLevel,this,canUsePortal(false));}finally{getAbilities().invulnerable=was;} + if(through){travel=entry.getX()+","+entry.getY()+","+entry.getZ();setPortalCooldown();} + else if(portalProcess.hasExpired())portalProcess=null; + } + } void clock()throws Exception{sceneLevel.time++;tickCount++;if(cooldown.getInt(this)>0)cooldown.setInt(this,cooldown.getInt(this)-1);if(hurtTime>0)hurtTime--;} void playerMovementTick(Vec3 input,boolean jumping){ preparedInput=true;xxa=(float)input.x;yya=0;zza=(float)input.z;setJumping(jumping); @@ -257,6 +272,8 @@ public final class VanillaSceneMotionOracle { p.onGround(),noBlocks.getBoolean(p),pos(support.get(p)),Double.doubleToLongBits(p.fallDistance),pos(last.get(p)),p.needsSync,p.syncPosition,Float.floatToIntBits(storedSpeed.getFloat(p)),delay.getInt(p),Float.floatToIntBits(p.yHeadRot),trigger.getInt(p),grace.getInt(p),impact.get(p)==null?"none":vectorBits((Vec3)impact.get(p)),String.join(";",attributes)); out.println("events "+String.join(" | ",p.events));p.events.clear(); out.println("block "+Block.getId(p.level().getBlockState(new BlockPos(25,3,25)))+" frozen "+p.frozen+" "+p.isInPowderSnow+" "+p.wasInPowderSnow+" "+vectorBits((Vec3)stuck.get(p))); + var pp=p.portalProcess; + out.println("portal "+p.getPortalCooldown()+" "+(pp==null?"none":pp.getEntryPosition().getX()+","+pp.getEntryPosition().getY()+","+pp.getEntryPosition().getZ()+" "+pp.getPortalTime()+" "+pp.isInsidePortalThisTick())+" "+(p.travel==null?"-":p.travel));p.travel=null; out.printf("health %08x %08x %08x %d %d %08x %d %d %s %d %s %s %s %s %s %d%n", Float.floatToIntBits(p.getHealth()),Float.floatToIntBits(p.getAbsorptionAmount()),Float.floatToIntBits(foodExhaustion.getFloat(p.getFoodData())), noAction.getInt(p),cooldown.getInt(p),Float.floatToIntBits(lastHurt.getFloat(p)),p.hurtDuration,p.hurtTime,sourceName((DamageSource)lastDamage.get(p)),lastStamp.getLong(p),healthDead.getBoolean(p),p.syncVelocity, @@ -373,6 +390,7 @@ public final class VanillaSceneMotionOracle { ((EntityEquipment)field(LivingEntity.class,"equipment").get(p)).set(net.minecraft.world.entity.EquipmentSlot.FEET,stack); } case "frozen"->p.frozen=op.get("value").getAsInt(); + case "portal_tick"->p.portalTick(op.get("creative").getAsBoolean()); case "weaving"->p.weaving=op.get("value").getAsBoolean(); case "flying"->{var a=p.getAbilities();a.mayfly=a.flying=op.get("value").getAsBoolean();} case "trigger"->trigger.setInt(p,op.get("value").getAsInt()); diff --git a/tools/test_native_scene_motion.py b/tools/test_native_scene_motion.py index dd8270f7c..59d49c8e1 100644 --- a/tools/test_native_scene_motion.py +++ b/tools/test_native_scene_motion.py @@ -189,8 +189,47 @@ def stuck_corpus(): ops += [tick(*walk) for _ in range(40)]+[op('flying',False)]+[tick(*walk) for _ in range(30)] yield dict(position=vec((25.5,4.5,23.5)),ops=ops) +def portal_corpus(): + """A nether portal in the player's path, ticked as Entity.handlePortal then + aiStep with the real applyEffectsFromBlocks (NetherPortalBlock.entityInside: + setAsInsidePortal): the 80-tick wait in survival, the creative delay, the + cooldown a portal keeps resetting, decay after stepping out, re-entering.""" + portal=[(x,y,25) for x in (25,26) for y in (4,5,6)] + def place(): + return [op('block',name='minecraft:nether_portal',position=list(p),properties={'axis':'x'}) for p in portal] + def restore(): + return [op('block',name='minecraft:air',position=list(p)) for p in portal] + def tick(creative,forward=0.,strafe=0.,jump=False): + return [op('portal_tick',creative=creative),op('snow_tick',vec((strafe,0,forward)),jumping=jump)] + rng=random.Random(0x504f5254) + for creative in [False,True]: + # Standing in it: through, then held by the cooldown, then walking out. + for start in [(25.5,4,25.5),(26.2,4,25.5),(25.5,4,25.1)]: + ops=[op('yaw',single(0))]+place() + for i in range(140): + ops += tick(creative,.98 if i>=110 else 0) + ops += restore() + yield dict(position=vec(start),ops=ops) + # Back and forth across it: decay outside, the entry block moving. + for pattern in range(6): + ops=[op('seed',rng.randrange(1<<31)),op('yaw',single(rng.choice([0,0,90,180])))]+place() + for i in range(160): + phase=(i//rng.choice([3,7,12,20]))%2 + ops += tick(creative,.98 if phase else -.98,rng.choice([0,0,.5]),i%17==0) + ops += restore() + yield dict(position=vec((25.5,4,23.8)),ops=ops) + # Out after going through: the leftover process decays, re-entering early. + for gap in [2,5,12,25]: + ops=[op('yaw',single(0))]+place() + ops += sum((tick(False) for _ in range(85)),[]) + ops += sum((tick(False,-.98) for _ in range(gap)),[]) + ops += sum((tick(False,.98 if id', v).hex() for v in position], 'dims': list(dims), + 'reset_forward': kind not in ('minecraft:item', 'minecraft:arrow')}, 'border': border} + + +def main(): + parser = h.argument_parser(__doc__) + args = parser.parse_args() + if args.count == 40000: + args.count = 1500 + lock, jars, libraries = base.verify_artifacts() + facts = h.load_facts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + work = lab.LOCAL / 'nether-portal-parity' + work.mkdir(parents=True, exist_ok=True) + all_cases = list(cases(facts, args.count, args.seed)) + (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases)) + classes = work / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + java_root = lab.ROOT / 'mods/horizon/src/test/java' + h.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn', + '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaPortalOracle.java')]) + h.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPortalOracle', + str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) + h.run(['cargo', 'run', '-q', '--release', '-p', 'horizon-world', '--example', 'portal_travel_fixture', '--', + str(resources), str(work / 'cases.jsonl'), str(work / 'rust.txt')], cwd=lab.ROOT) + native = h.split_cases((work / 'native.txt').read_text(), ()) + rust = h.split_cases((work / 'rust.txt').read_text(), ()) + assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) + groups, errors = {}, {} + created = found = 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 + if any(line.startswith('set ') for line in a): + created += 1 + elif not any(line == 'dest none' for line in a): + found += 1 + if sorted(a) != sorted(b): + key = f"{case['from']} {case['entity']['type']} {'pois' if case['pois'] else 'no pois'}" + groups.setdefault(key, []).append((case, a, b)) + for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])): + print(f'oracle error x{len(entries)}: {name}') + 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(f" case entry={case['entry']} entity={case['entity']} border={case['border']} pois={len(case['pois'])}") + print(' native ' + ' | '.join(sorted(a))[:1500]) + print(' rust ' + ' | '.join(sorted(b))[:1500]) + 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 linked to an existing portal {found} times and built one {created} times') + h.finish(total + skipped) + + +if __name__ == '__main__': + main()