diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 65536d710..6e8089e9d 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -10,6 +10,8 @@ use crate::{ use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::block_collision::BlockCollisionRegistry; +mod fluids; + #[derive(Clone, Debug)] pub struct ItemEntity { pub health: i32, @@ -165,18 +167,16 @@ impl ItemEntity { facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, no_physics: bool, + fluids: &crate::motion::FluidResources, ) -> bool { self.ticks += 1; self.previous = self.position; if self.pickup_delay > 0 && self.pickup_delay != u32::MAX { self.pickup_delay -= 1; } - let eye = world.block( - self.position.x.floor() as i32, - (self.position.y + 0.1).floor() as i32, - self.position.z.floor() as i32, - ); - let in_water = facts.get(eye).fluid == Fluid::Water; + // Entity.baseTick pushes before ItemEntity applies buoyancy and moves. + let (water_height, lava_height) = self.update_fluids(world, fluids); + let in_water = water_height > f64::from(0.1f32); if in_water { // ItemEntity.setUnderwaterMovement self.velocity = Vec3::new( @@ -184,7 +184,7 @@ impl ItemEntity { self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 }, self.velocity.z * 0.99, ); - } else if facts.get(eye).fluid == Fluid::Lava { + } else if lava_height > f64::from(0.1f32) { self.velocity = Vec3::new( self.velocity.x * 0.95, self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 }, @@ -245,6 +245,8 @@ impl ItemEntity { } } self.age += 1; + // ItemEntity.tick refreshes immersion and pushes again after moving. + self.update_fluids(world, fluids); self.age < 6000 && self.position.y > -128.0 } /// `ItemEntity.isMergable` at `age`: a stack below its size whose pickup diff --git a/crates/horizon-client/src/entities/fluids.rs b/crates/horizon-client/src/entities/fluids.rs new file mode 100644 index 000000000..fffa0ae2b --- /dev/null +++ b/crates/horizon-client/src/entities/fluids.rs @@ -0,0 +1,216 @@ +//! Dropped-item immersion and currents through the shared vanilla fluid helpers. +use super::ItemEntity; +use crate::{ + motion::{FluidResources, FluidTags, LAVA, WATER}, + world::World, +}; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, +}; +use horizon_world::{ + entity_fluid::{ + CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership, + FluidSections, FluidTagId, + }, + fluid::{FluidHeightWorld, FluidKind, FluidState}, + fluid_flow::{FluidFlowWorld, flow_at}, + registry::BlockStateId, +}; +type Error = std::convert::Infallible; +struct ItemFluidWorld<'a> { + item: &'a mut ItemEntity, + world: &'a World, + fluids: &'a FluidResources, +} +impl ItemEntity { + pub(super) fn update_fluids(&mut self, world: &World, fluids: &FluidResources) -> (f64, f64) { + let mut interaction = EntityFluidInteraction::new([WATER, LAVA]); + let mut scene = ItemFluidWorld { + item: self, + world, + fluids, + }; + if interaction.update(&mut scene, false, 4096).is_err() { + return (0.0, 0.0); + } + let water_height = interaction.fluid_height(&scene, WATER); + let lava_height = interaction.fluid_height(&scene, LAVA); + let _ = interaction.apply_current(&mut scene, WATER, 0.014); + let _ = interaction.apply_current( + &mut scene, + LAVA, + if world.fast_lava { + 0.007 + } else { + 0.0023333333333333335 + }, + ); + (water_height, lava_height) + } +} +impl FluidMembership for ItemFluidWorld<'_> { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + FluidTags.fluid_in_tag(kind, tag) + } +} +impl CurrentTarget for ItemFluidWorld<'_> { + type Error = Error; + fn is_player_class(&self) -> bool { + false + } + fn velocity(&mut self) -> Result { + Ok(self.item.velocity) + } + fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Error> { + let v = self.item.velocity; + let sum = Vec3::new(v.x + delta.x, v.y + delta.y, v.z + delta.z); + if delta.is_finite() && sum.is_finite() { + self.item.velocity = sum; + } + Ok(()) + } +} +impl FluidInteractionWorld for ItemFluidWorld<'_> { + type Error = Error; + type Chunk = (); + fn interaction_box(&mut self) -> Result, Error> { + Ok(Some( + self.item.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)), + )) + } + fn loaded_chunk(&mut self, x: i32, z: i32) -> Result, Error> { + Ok(self.world.chunks.contains_key(&(x, z)).then_some(())) + } + fn chunk_sections(&mut self, _: ()) -> Result, Error> { + static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS]; + Ok(FluidSections { + minimum_section_y: crate::chunk::MIN_Y >> 4, + has_fluid: &SECTIONS, + }) + } + fn bounding_box_min_y(&self) -> f64 { + self.item.position.y + } + fn block_x(&self) -> i32 { + self.item.position.x.floor() as i32 + } + fn eye_y(&mut self) -> Result { + Ok(self.item.position.y + f64::from(0.2125f32)) + } + fn block_z(&self) -> i32 { + self.item.position.z.floor() as i32 + } + fn fluid_state(&mut self, p: BlockPos) -> Result { + Ok(self.fluids.fluid(self.world.block(p.x, p.y, p.z))) + } + fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.height_at(self, [p.x, p.y, p.z]) + } + fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.camera_height_at(self, [p.x, p.y, p.z]) + } + fn flow(&mut self, f: FluidState, p: BlockPos) -> Result { + flow_at(self, f, p) + } +} +impl FluidHeightWorld for ItemFluidWorld<'_> { + type Error = Error; + fn fluid(&mut self, p: [i32; 3]) -> Result { + Ok(self.fluids.fluid(self.world.block(p[0], p[1], p[2]))) + } + fn sturdy_down(&mut self, p: [i32; 3]) -> Result { + let state = self.world.block(p[0], p[1], p[2]); + Ok(self.fluids.sturdy(state, Direction::Down)) + } +} +impl FluidFlowWorld for ItemFluidWorld<'_> { + type Error = Error; + type Block = BlockStateId; + fn fluid(&mut self, p: BlockPos) -> Result { + Ok(self.fluids.fluid(self.world.block(p.x, p.y, p.z))) + } + fn block(&mut self, p: BlockPos) -> Result { + Ok(self.world.block(p.x, p.y, p.z)) + } + fn blocks_fluid_flow(&self, s: BlockStateId) -> bool { + self.fluids.blocks_flow(s) + } + fn is_ice_class(&self, s: BlockStateId) -> bool { + self.fluids.ice(s) + } + fn is_face_sturdy( + &mut self, + s: BlockStateId, + _: BlockPos, + d: Direction, + ) -> Result { + Ok(self.fluids.sturdy(s, d)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn items_follow_flowing_water_but_still_water_has_no_horizontal_push() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = crate::assets::Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap(); + let fluids = FluidResources::new(&assets, &facts).unwrap(); + let collision = crate::collisions::load(&root, assets.registry).unwrap(); + let mut world = World::test_scene(&assets, &render, 3).unwrap(); + let stone = assets.registry.default_state("minecraft:stone").unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + let mut state = assets.registry.state(water).unwrap().clone(); + state.properties.insert("level".into(), "1".into()); + let flowing = assets.registry.resolve(&state).unwrap(); + for x in 19..=21 { + for z in 19..=21 { + world.set(x, 3, z, stone).unwrap(); + world.set(x, 4, z, water).unwrap(); + } + } + let at = Vec3::new(20.5, 4.0, 20.5); + let item = ItemEntity { + id: 1, + health: 5, + fire_ticks: 0, + stack: crate::items::ItemStack { + item: "minecraft:sugar_cane".into(), + count: 1, + damage: 0, + extra: None, + }, + thrower: None, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: false, + age: 0, + pickup_delay: 0, + bob_offset: 0.0, + ticks: 0, + }; + let mut still = item.clone(); + assert!(still.tick(&world, &facts, &collision, false, &fluids)); + assert_eq!(still.position.x, at.x); + assert_eq!(still.velocity.x, 0.0); + world.set(21, 4, 20, flowing).unwrap(); + let mut carried = item; + assert!(carried.tick(&world, &facts, &collision, false, &fluids)); + // First push is damped by buoyancy before motion, second follows drag. + assert!((carried.position.x - at.x - 0.014 * 0.99).abs() < 1e-12); + assert!((carried.velocity.x - (0.014 * 0.99 * 0.98 + 0.014)).abs() < 1e-12); + for _ in 0..20 { + carried.tick(&world, &facts, &collision, false, &fluids); + } + assert!(carried.position.x > at.x + 0.5); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8591c721f..65945d49b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2272,7 +2272,13 @@ impl Game<'_> { let speed = self.world.random.next_float() * 0.2 + 0.1; item.move_towards_closest_space(&self.world, self.res.facts(), speed); } - let alive = item.tick(&self.world, self.res.facts(), self.collision, no_physics); + let alive = item.tick( + &self.world, + self.res.facts(), + self.collision, + no_physics, + &self.res.motion().fluids, + ); cells.moved(i, item.previous, item.position); // ItemEntity.tick: merge every 2 ticks while moving between // blocks, every 40 otherwise, before the lifetime check. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 07ab0c80d..20c307720 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3505,7 +3505,7 @@ impl Game<'_> { // ticks), and only the server removes it. let (world, facts, collision) = (&self.world, self.res.facts(), self.collision); for d in self.dropped.iter_mut().filter(|_| running) { - d.tick(world, facts, collision, false); + d.tick(world, facts, collision, false, &self.res.motion().fluids); } head_lerps.retain(|_, (_, steps)| *steps > 0); for (item, ticks, at, eye, pitch, yaw) in using { diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index a6f97981e..0bce8927c 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -44,7 +44,7 @@ use std::{ pub(crate) mod environment; mod fluids; -pub use fluids::{FluidResources, LAVA, PlayerFluids, WATER}; +pub use fluids::{FluidResources, FluidTags, LAVA, PlayerFluids, WATER}; pub struct MotionResources { pub attributes: Arc, diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index 89affeb64..894e6d907 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -103,10 +103,10 @@ fn is_tagged(kind: FluidKind, tag: FluidTagId) -> bool { } impl PlayerMotion { pub fn fluid_height(&self, tag: FluidTagId) -> f64 { - self.fluids.interaction.fluid_height(&Membership, tag) + self.fluids.interaction.fluid_height(&FluidTags, tag) } pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool { - self.fluids.interaction.is_eye_in_fluid(&Membership, tag) + self.fluids.interaction.is_eye_in_fluid(&FluidTags, tag) } /// `LocalPlayer.isUnderWater`: `wasUnderwater`, the eye sample `Player.tick` /// takes before the base tick (`Entity.isUnderWater` also needs the body @@ -116,11 +116,12 @@ impl PlayerMotion { } /// `Entity.isInLava`. pub fn is_in_lava(&self) -> bool { - !self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA) + !self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&FluidTags, LAVA) } } -struct Membership; -impl FluidMembership for Membership { +/// Which fluids `FluidTags.WATER` and `FluidTags.LAVA` hold. +pub struct FluidTags; +impl FluidMembership for FluidTags { fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { is_tagged(kind, tag) } diff --git a/tools/test_entity_fluid_parity.py b/tools/test_entity_fluid_parity.py index b37a3e11d..f8cbf918d 100644 --- a/tools/test_entity_fluid_parity.py +++ b/tools/test_entity_fluid_parity.py @@ -29,6 +29,15 @@ def corpus(): if v[k] is not None:v[k]=[bits(n) for n in v[k]] return v def row(ops,player=False,order=(0,1,2)):return dict(ops=ops,player=player,order=order) + # Dropped items: the 0.25-wide box is deflated by Entity before scanning. + # Cover surface grazing, buoyancy depth, cell boundaries and repeated pushes. + for x in [.5, 1.0, 15.99]: + for y in [0, .1, .7, 8/9-.1, 8/9-.001, 8/9, 1]: + for flow in [(0,0,0),(1,0,0),(-1,0,1),(0,-1,0)]: + update=op(bounds=[x-.124,y+.001,.376,x+.124,y+.249,.624], + base_y=y,eye=y+.2125,block=[int(x),int(y),0], + default=cell(flow=flow)) + yield row([update,op(mode='apply'),update,op(mode='apply')]) values=[-float('inf'),-1,-.0,0,.1,.39999998,.4,.40000004,8/9,1,2,float('inf'),float('nan')] for kind in range(5): for height in values: