Water cancels the player's fall damage (#180)
The player's movement treated every fluid as empty: is_in_water was always false, LivingEntity.checkFallDamage's updateFluidInteraction was a no-op and Entity.move's fall-reset ray ignored water. A player landing in water (or a waterlogged block, a bubble column, kelp) still took the whole fall. Bind vanilla's Entity.updateFluidInteraction to the player over the existing horizon-world kernels (EntityFluidInteraction heights, eyes and currents, entity_fluid_tick, water_splash, fluid_flow): run it in the base tick and from checkFallDamage, read wasTouchingWater for isInWater, query the water's (first-query cached) shape in the FALLDAMAGE_RESETTING ray, halve the fall in lava after the first tick, and play the splash sound with bubble and splash particles. The scene motion harness gains water/lava fixtures (fluid_tick plus scripted falls through the real Entity.move) against the real vanilla updateFluidInteraction with the #water/#lava tags bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,7 +4,7 @@ use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
collisions,
|
||||
motion::{MotionEvent, MotionResources, MotionWorld, PlayerMotion},
|
||||
motion::{LAVA, MotionEvent, MotionResources, MotionWorld, PlayerMotion, WATER},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
@@ -174,6 +174,31 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
|
||||
velocity.y.to_bits(),
|
||||
velocity.z.to_bits()
|
||||
)),
|
||||
MotionEvent::Splash {
|
||||
high_speed,
|
||||
volume,
|
||||
pitch,
|
||||
} => Some(format!(
|
||||
"sound {} entity {:08x} {:08x}",
|
||||
if *high_speed { "splash-high" } else { "splash" },
|
||||
volume.to_bits(),
|
||||
pitch.to_bits()
|
||||
)),
|
||||
MotionEvent::SplashParticle {
|
||||
bubble,
|
||||
position,
|
||||
velocity,
|
||||
} => Some(format!(
|
||||
"splash-particle {} {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}",
|
||||
if *bubble { "bubble" } else { "splash" },
|
||||
position.x.to_bits(),
|
||||
position.y.to_bits(),
|
||||
position.z.to_bits(),
|
||||
velocity.x.to_bits(),
|
||||
velocity.y.to_bits(),
|
||||
velocity.z.to_bits()
|
||||
)),
|
||||
MotionEvent::SplashEvent => Some("splash-event".into()),
|
||||
// The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so.
|
||||
MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()),
|
||||
MotionEvent::Waypoint { receiver, enabled } => Some(format!(
|
||||
@@ -415,6 +440,9 @@ fn main() -> Result<()> {
|
||||
p,
|
||||
)?;
|
||||
}
|
||||
// Entity.baseTick's fluid phase alone (wasEyeInWater,
|
||||
// updateFluidInteraction, lava fall halving, firstTick).
|
||||
"fluid_tick" => world.fluid_base_tick()?,
|
||||
"travel" => world.travel_in_air(vector(&op["value"]))?,
|
||||
"tick" => {
|
||||
let v = vector(&op["value"]);
|
||||
@@ -541,14 +569,20 @@ fn main() -> Result<()> {
|
||||
let stuck = player.stuck_multiplier;
|
||||
writeln!(
|
||||
out,
|
||||
"block {} frozen {} {} {} {:016x},{:016x},{:016x}",
|
||||
"block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x}",
|
||||
check_block.0,
|
||||
player.ticks_frozen,
|
||||
player.in_powder_snow,
|
||||
player.was_in_powder_snow,
|
||||
stuck.x.to_bits(),
|
||||
stuck.y.to_bits(),
|
||||
stuck.z.to_bits()
|
||||
stuck.z.to_bits(),
|
||||
player.fluids.was_touching_water,
|
||||
player.fluids.was_eye_in_water,
|
||||
player.is_eye_in_fluid(WATER),
|
||||
player.fluids.first_tick,
|
||||
player.fluid_height(WATER).to_bits(),
|
||||
player.fluid_height(LAVA).to_bits()
|
||||
)?;
|
||||
writeln!(
|
||||
out,
|
||||
|
||||
@@ -2852,6 +2852,8 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.flatten()
|
||||
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)));
|
||||
// The dimension's FAST_LAVA: the Nether's lava pushes harder.
|
||||
player.fluids.fast_lava = self.dim == Dim::Nether;
|
||||
let grounded = player.ground.on_ground;
|
||||
let before = (
|
||||
grounded,
|
||||
@@ -2943,6 +2945,35 @@ impl Game<'_> {
|
||||
position,
|
||||
fall_distance,
|
||||
} => self.smash_landing_particles(state, position, fall_distance),
|
||||
MotionEvent::Splash {
|
||||
high_speed,
|
||||
volume,
|
||||
pitch,
|
||||
} => {
|
||||
let name = if high_speed {
|
||||
"minecraft:entity.player.splash.high_speed"
|
||||
} else {
|
||||
"minecraft:entity.player.splash"
|
||||
};
|
||||
self.audio.play(name, Some(feet), volume, pitch);
|
||||
}
|
||||
MotionEvent::SplashParticle {
|
||||
bubble,
|
||||
position,
|
||||
velocity,
|
||||
} => {
|
||||
use horizon_client::particles::{ParticleOptions, ParticleType};
|
||||
let kind = if bubble {
|
||||
ParticleType::Bubble
|
||||
} else {
|
||||
ParticleType::Splash
|
||||
};
|
||||
self.particles.add(
|
||||
&ParticleOptions::simple(kind),
|
||||
[position.x, position.y, position.z],
|
||||
[velocity.x, velocity.y, velocity.z],
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,7 +219,7 @@ impl FallDamageWorld for MotionWorld<'_, '_, '_> {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
type State = BlockStateId;
|
||||
fn is_in_water(&mut self) -> Result<bool> {
|
||||
Ok(false)
|
||||
Ok(self.player.fluids.was_touching_water)
|
||||
}
|
||||
fn fall_distance(&self) -> f64 {
|
||||
self.player.fall_distance
|
||||
@@ -253,8 +253,8 @@ impl FallDamageWorld for MotionWorld<'_, '_, '_> {
|
||||
}
|
||||
impl LivingLandingWorld for MotionWorld<'_, '_, '_> {
|
||||
fn update_fluid_interaction(&mut self) -> Result<bool> {
|
||||
Ok(false)
|
||||
} // dry scene
|
||||
self.update_fluids()
|
||||
}
|
||||
fn is_server_level(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
@@ -43,6 +43,9 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
mod fluids;
|
||||
pub use fluids::{FluidResources, LAVA, PlayerFluids, WATER};
|
||||
|
||||
pub struct MotionResources {
|
||||
pub attributes: Arc<Catalog>,
|
||||
pub blocks: BoundMovementProperties,
|
||||
@@ -50,6 +53,7 @@ pub struct MotionResources {
|
||||
pub fall_reset: BTreeSet<String>,
|
||||
pub landing: BlockLandingRegistry,
|
||||
pub health: crate::health::HealthResources,
|
||||
pub fluids: FluidResources,
|
||||
}
|
||||
impl MotionResources {
|
||||
pub fn load(root: &Path, assets: &Assets) -> Result<Self> {
|
||||
@@ -86,6 +90,7 @@ impl MotionResources {
|
||||
Ok(Self {
|
||||
landing: crate::landing::load(root, &properties)?,
|
||||
health: crate::health::HealthResources::load(root)?,
|
||||
fluids: FluidResources::load(root, assets)?,
|
||||
attributes,
|
||||
blocks: properties.bind(&MovementTags {
|
||||
fences: tag("minecraft:fences")?,
|
||||
@@ -150,6 +155,21 @@ pub enum MotionEvent {
|
||||
position: BlockPos,
|
||||
fall_distance: f64,
|
||||
},
|
||||
/// `Entity.doWaterSplashEffect`: the player's splash (or high-speed
|
||||
/// splash) sound at its position...
|
||||
Splash {
|
||||
high_speed: bool,
|
||||
volume: f32,
|
||||
pitch: f32,
|
||||
},
|
||||
/// ...its BUBBLE (else SPLASH) particles...
|
||||
SplashParticle {
|
||||
bubble: bool,
|
||||
position: Vec3,
|
||||
velocity: Vec3,
|
||||
},
|
||||
/// ...and the SPLASH game event.
|
||||
SplashEvent,
|
||||
}
|
||||
pub struct PlayerMotion {
|
||||
pub position: Vec3,
|
||||
@@ -213,6 +233,8 @@ pub struct PlayerMotion {
|
||||
pub health: crate::health::PlayerHealth,
|
||||
/// Status effects and armor protection seen by movement and damage.
|
||||
pub status: crate::effects::StatusFlags,
|
||||
/// Water and lava around the player (`Entity.fluidInteraction`).
|
||||
pub fluids: PlayerFluids,
|
||||
/// `Entity.isInPowderSnow` / `wasInPowderSnow`.
|
||||
pub in_powder_snow: bool,
|
||||
pub was_in_powder_snow: bool,
|
||||
@@ -313,6 +335,7 @@ impl PlayerMotion {
|
||||
sync_position: false,
|
||||
events: Vec::new(),
|
||||
attributes,
|
||||
fluids: PlayerFluids::default(),
|
||||
in_powder_snow: false,
|
||||
was_in_powder_snow: false,
|
||||
ticks_frozen: 0,
|
||||
@@ -591,6 +614,7 @@ impl MotionWorld<'_, '_, '_> {
|
||||
// Entity.baseTick
|
||||
self.player.was_in_powder_snow = self.player.in_powder_snow;
|
||||
self.player.in_powder_snow = false;
|
||||
self.fluid_base_tick()?;
|
||||
self.player.old_position = self.player.position;
|
||||
if self.player.jump_trigger_time > 0 {
|
||||
self.player.jump_trigger_time -= 1;
|
||||
@@ -1334,15 +1358,21 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
|
||||
self.player.fall_distance
|
||||
}
|
||||
fn fall_reset_clip(&mut self, from: Vec3, to: Vec3) -> Result<bool> {
|
||||
// Every fluid in this controlled scene is empty. Tagged reset blocks use
|
||||
// a full block in ClipContext.FALLDAMAGE_RESETTING, not their collider.
|
||||
// ClipContext.Block.FALLDAMAGE_RESETTING: tagged reset blocks are a full
|
||||
// block, not their collider; ClipContext.Fluid.WATER: the water's shape.
|
||||
// Both shapes are queried for every visited block (the water's first
|
||||
// query fixes its cached shape), either one hitting ends the ray.
|
||||
let hit = traverse_blocks(from, to, 1_000_000, |p| {
|
||||
let water = match self.water_clip(from, to, p) {
|
||||
Ok(hit) => hit,
|
||||
Err(e) => return Some(Err(e)),
|
||||
};
|
||||
let name = &self.assets.registry.state(self.block(p)).unwrap().name;
|
||||
(self.resources.fall_reset.contains(name)
|
||||
&& VoxelShape::block().clip(from, to, p).is_some())
|
||||
.then_some(())
|
||||
let reset = self.resources.fall_reset.contains(name)
|
||||
&& VoxelShape::block().clip(from, to, p).is_some();
|
||||
(water || reset).then_some(Ok(()))
|
||||
})?;
|
||||
Ok(hit.is_some())
|
||||
hit.transpose().map(|h| h.is_some())
|
||||
}
|
||||
fn reset_fall_distance(&mut self) -> Result<()> {
|
||||
self.player.fall_distance = 0.0;
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
//! The player's fluid immersion over the resident scene: `Entity.updateFluidInteraction`
|
||||
//! (water, waterlogged blocks, bubble columns and lava, with their currents), the
|
||||
//! water-entry splash and the fall resets that hinge on touching water.
|
||||
use super::*;
|
||||
use horizon_world::{
|
||||
entity_fluid::{
|
||||
CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership,
|
||||
FluidSections, FluidTagId,
|
||||
},
|
||||
entity_fluid_tick::{self, EntityFluidTickWorld},
|
||||
fluid::{FluidHeightWorld, FluidKind, FluidState, FluidStateTable},
|
||||
fluid_flow::{FluidFlowWorld, flow_at},
|
||||
fluid_shape::FluidShapeCache,
|
||||
water_splash::{self, SplashParticle, WaterSplashWorld},
|
||||
};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// `FluidTags.WATER` and `FluidTags.LAVA`, the fluids with a current.
|
||||
pub const WATER: FluidTagId = FluidTagId(0);
|
||||
pub const LAVA: FluidTagId = FluidTagId(1);
|
||||
|
||||
/// Per-state fluid facts the player's immersion and fall-reset rays read.
|
||||
pub struct FluidResources {
|
||||
states: FluidStateTable,
|
||||
/// `isFaceSturdy(FULL)` per `Direction` (bit = ordinal).
|
||||
sturdy: Vec<u8>,
|
||||
/// `#minecraft:blocks_fluid_flow` membership.
|
||||
blocks_flow: Vec<bool>,
|
||||
/// `IceBlock` and its subclasses.
|
||||
ice: Vec<bool>,
|
||||
/// `FlowingFluid.shapes`: the shape of the first query of each fluid
|
||||
/// state, kept for the whole process like the registered fluid's map.
|
||||
pub shapes: Mutex<FluidShapeCache>,
|
||||
}
|
||||
impl FluidResources {
|
||||
pub fn load(root: &Path, assets: &Assets) -> Result<Self> {
|
||||
let facts = crate::blocks::BlockFacts::load(root, assets.registry)?;
|
||||
Ok(Self {
|
||||
states: FluidStateTable::new(assets.registry)?,
|
||||
sturdy: facts.states.iter().map(|s| s.sturdy_full).collect(),
|
||||
blocks_flow: facts
|
||||
.states
|
||||
.iter()
|
||||
.map(|s| assets.blocks_fluid_flow.contains(&*s.name))
|
||||
.collect(),
|
||||
ice: facts.states.iter().map(|s| s.has_class("IceBlock")).collect(),
|
||||
shapes: Mutex::new(FluidShapeCache::default()),
|
||||
})
|
||||
}
|
||||
pub fn fluid(&self, state: BlockStateId) -> FluidState {
|
||||
self.states.get(state).unwrap_or(FluidState::EMPTY)
|
||||
}
|
||||
fn sturdy(&self, state: BlockStateId, d: Direction) -> bool {
|
||||
self.sturdy
|
||||
.get(state.0 as usize)
|
||||
.is_some_and(|s| s & 1 << d as u8 != 0)
|
||||
}
|
||||
}
|
||||
/// The player's `EntityFluidInteraction` and the water flags around it.
|
||||
pub struct PlayerFluids {
|
||||
pub interaction: EntityFluidInteraction,
|
||||
/// `Entity.wasTouchingWater` (`isInWater`).
|
||||
pub was_touching_water: bool,
|
||||
/// `Entity.wasEyeInWater`.
|
||||
pub was_eye_in_water: bool,
|
||||
/// `Entity.firstTick`: no splash, and no lava, until the first base tick ends.
|
||||
pub first_tick: bool,
|
||||
/// The dimension's `FAST_LAVA` (the Nether), set by the game.
|
||||
pub fast_lava: bool,
|
||||
}
|
||||
impl Default for PlayerFluids {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
interaction: EntityFluidInteraction::new([WATER, LAVA]),
|
||||
was_touching_water: false,
|
||||
was_eye_in_water: false,
|
||||
first_tick: true,
|
||||
fast_lava: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn is_tagged(kind: FluidKind, tag: FluidTagId) -> bool {
|
||||
if tag == WATER {
|
||||
matches!(kind, FluidKind::Water | FluidKind::FlowingWater)
|
||||
} else {
|
||||
matches!(kind, FluidKind::Lava | FluidKind::FlowingLava)
|
||||
}
|
||||
}
|
||||
impl PlayerMotion {
|
||||
pub fn fluid_height(&self, tag: FluidTagId) -> f64 {
|
||||
self.fluids.interaction.fluid_height(&Membership, tag)
|
||||
}
|
||||
pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool {
|
||||
self.fluids.interaction.is_eye_in_fluid(&Membership, tag)
|
||||
}
|
||||
/// `Entity.isInLava`.
|
||||
pub fn is_in_lava(&self) -> bool {
|
||||
!self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA)
|
||||
}
|
||||
}
|
||||
struct Membership;
|
||||
impl FluidMembership for Membership {
|
||||
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
|
||||
is_tagged(kind, tag)
|
||||
}
|
||||
}
|
||||
impl MotionWorld<'_, '_, '_> {
|
||||
fn fluid_at(&self, p: BlockPos) -> FluidState {
|
||||
self.resources.fluids.fluid(self.block(p))
|
||||
}
|
||||
/// `Entity.baseTick`'s fluid phase: `wasEyeInWater`, `updateFluidInteraction`,
|
||||
/// the lava's fall halving, and the end of the first tick.
|
||||
pub fn fluid_base_tick(&mut self) -> Result<()> {
|
||||
self.player.fluids.was_eye_in_water = self.player.is_eye_in_fluid(WATER);
|
||||
self.update_fluids()?;
|
||||
if self.player.is_in_lava() {
|
||||
self.player.fall_distance *= 0.5;
|
||||
}
|
||||
self.player.fluids.first_tick = false;
|
||||
Ok(())
|
||||
}
|
||||
/// `Entity.updateFluidInteraction`: immersion heights, then touching water
|
||||
/// resets the fall and splashes on entry, then the currents push.
|
||||
pub fn update_fluids(&mut self) -> Result<bool> {
|
||||
let mut interaction = std::mem::take(&mut self.player.fluids.interaction);
|
||||
let result = entity_fluid_tick::update(&mut interaction, self, WATER, LAVA, 1_000_000);
|
||||
self.player.fluids.interaction = interaction;
|
||||
result.map_err(|e| e.to_string().into())
|
||||
}
|
||||
/// `ClipContext.Fluid.WATER` in a fall-reset ray: the water's shape.
|
||||
pub(super) fn water_clip(&mut self, from: Vec3, to: Vec3, p: BlockPos) -> Result<bool> {
|
||||
let fluid = self.fluid_at(p);
|
||||
if !is_tagged(fluid.kind(), WATER) {
|
||||
return Ok(false);
|
||||
}
|
||||
let resources = self.resources;
|
||||
let shape = resources
|
||||
.fluids
|
||||
.shapes
|
||||
.lock()
|
||||
.map_err(|_| "fluid shape cache poisoned")?
|
||||
.shape(self, fluid, p)?;
|
||||
Ok(shape.clip(from, to, p).is_some())
|
||||
}
|
||||
}
|
||||
impl FluidMembership for MotionWorld<'_, '_, '_> {
|
||||
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
|
||||
is_tagged(kind, tag)
|
||||
}
|
||||
}
|
||||
impl CurrentTarget for MotionWorld<'_, '_, '_> {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
fn is_player_class(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn velocity(&mut self) -> Result<Vec3> {
|
||||
Ok(self.player.velocity)
|
||||
}
|
||||
fn add_delta_movement(&mut self, delta: Vec3) -> Result<()> {
|
||||
// Entity.addDeltaMovement and setDeltaMovement keep only finite values.
|
||||
let v = self.player.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.player.velocity = sum;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl FluidInteractionWorld for MotionWorld<'_, '_, '_> {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
type Chunk = ();
|
||||
fn interaction_box(&mut self) -> Result<Option<Aabb>> {
|
||||
// Entity.getFluidInteractionBox (not riding).
|
||||
Ok(Some(
|
||||
self.player.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)),
|
||||
))
|
||||
}
|
||||
fn loaded_chunk(&mut self, x: i32, z: i32) -> Result<Option<()>> {
|
||||
Ok(self.scene.chunks.contains_key(&(x, z)).then_some(()))
|
||||
}
|
||||
fn chunk_sections(&mut self, _: ()) -> Result<FluidSections<'_>> {
|
||||
// Resident sections keep no fluid count: scanning the box finds no
|
||||
// fluid where a section without fluid would have skipped it.
|
||||
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.player.bounds().min_position().y
|
||||
}
|
||||
fn block_x(&self) -> i32 {
|
||||
self.player.position.x.floor() as i32
|
||||
}
|
||||
fn eye_y(&mut self) -> Result<f64> {
|
||||
Ok(self.player.position.y + f64::from(self.player.dimensions.eye_height))
|
||||
}
|
||||
fn block_z(&self) -> i32 {
|
||||
self.player.position.z.floor() as i32
|
||||
}
|
||||
fn fluid_state(&mut self, p: BlockPos) -> Result<FluidState> {
|
||||
Ok(self.fluid_at(p))
|
||||
}
|
||||
fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32> {
|
||||
f.height_at(self, [p.x, p.y, p.z])
|
||||
}
|
||||
fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32> {
|
||||
f.camera_height_at(self, [p.x, p.y, p.z])
|
||||
}
|
||||
fn flow(&mut self, f: FluidState, p: BlockPos) -> Result<Vec3> {
|
||||
flow_at(self, f, p)
|
||||
}
|
||||
}
|
||||
impl EntityFluidTickWorld for MotionWorld<'_, '_, '_> {
|
||||
/// `Player.isPushedByFluid`: not while flying.
|
||||
fn is_pushed_by_fluid(&mut self) -> Result<bool> {
|
||||
Ok(!self.player.flying)
|
||||
}
|
||||
fn reset_fall_distance(&mut self) -> Result<()> {
|
||||
self.player.fall_distance = 0.0;
|
||||
Ok(())
|
||||
}
|
||||
fn was_touching_water(&self) -> bool {
|
||||
self.player.fluids.was_touching_water
|
||||
}
|
||||
fn first_tick(&self) -> bool {
|
||||
self.player.fluids.first_tick
|
||||
}
|
||||
fn water_splash(&mut self) -> Result<()> {
|
||||
water_splash::water_splash(self, 1_000_000).map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
fn set_was_touching_water(&mut self, value: bool) {
|
||||
self.player.fluids.was_touching_water = value;
|
||||
}
|
||||
fn fast_lava(&mut self) -> Result<bool> {
|
||||
Ok(self.player.fluids.fast_lava)
|
||||
}
|
||||
}
|
||||
impl FluidHeightWorld for MotionWorld<'_, '_, '_> {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
fn fluid(&mut self, p: [i32; 3]) -> Result<FluidState> {
|
||||
Ok(self.fluid_at(BlockPos::new(p[0], p[1], p[2])))
|
||||
}
|
||||
fn sturdy_down(&mut self, p: [i32; 3]) -> Result<bool> {
|
||||
let state = MotionWorld::block(self, BlockPos::new(p[0], p[1], p[2]));
|
||||
Ok(self.resources.fluids.sturdy(state, Direction::Down))
|
||||
}
|
||||
}
|
||||
impl FluidFlowWorld for MotionWorld<'_, '_, '_> {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
type Block = BlockStateId;
|
||||
fn fluid(&mut self, p: BlockPos) -> Result<FluidState> {
|
||||
Ok(self.fluid_at(p))
|
||||
}
|
||||
fn block(&mut self, p: BlockPos) -> Result<BlockStateId> {
|
||||
Ok(MotionWorld::block(self, p))
|
||||
}
|
||||
fn blocks_fluid_flow(&self, s: BlockStateId) -> bool {
|
||||
self.resources
|
||||
.fluids
|
||||
.blocks_flow
|
||||
.get(s.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
}
|
||||
fn is_ice_class(&self, s: BlockStateId) -> bool {
|
||||
self.resources
|
||||
.fluids
|
||||
.ice
|
||||
.get(s.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
}
|
||||
fn is_face_sturdy(&mut self, s: BlockStateId, _: BlockPos, d: Direction) -> Result<bool> {
|
||||
Ok(self.resources.fluids.sturdy(s, d))
|
||||
}
|
||||
}
|
||||
/// `Entity.doWaterSplashEffect` for the player: the world random draws the
|
||||
/// pitch and particle offsets.
|
||||
impl WaterSplashWorld for MotionWorld<'_, '_, '_> {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
type Entity = ();
|
||||
/// `Player.getSwimHighSpeedSplashSound` when true, else `getSwimSplashSound`.
|
||||
type Sound = bool;
|
||||
fn this_entity(&self) {}
|
||||
fn controlling_passenger(&mut self) -> Result<Option<()>> {
|
||||
Ok(None)
|
||||
}
|
||||
fn velocity(&mut self, _: ()) -> Result<Vec3> {
|
||||
Ok(self.player.velocity)
|
||||
}
|
||||
fn splash_sound(&mut self, high_speed: bool) -> Result<bool> {
|
||||
Ok(high_speed)
|
||||
}
|
||||
fn random_float(&mut self) -> Result<f32> {
|
||||
Ok(self.scene.random.next_float())
|
||||
}
|
||||
fn random_double(&mut self) -> Result<f64> {
|
||||
Ok(self.scene.random.next_double())
|
||||
}
|
||||
fn play_sound(&mut self, high_speed: bool, volume: f32, pitch: f32) -> Result<()> {
|
||||
self.player.events.push(MotionEvent::Splash {
|
||||
high_speed,
|
||||
volume,
|
||||
pitch,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn position(&self) -> Vec3 {
|
||||
self.player.position
|
||||
}
|
||||
fn width(&self) -> f32 {
|
||||
self.player.dimensions.width
|
||||
}
|
||||
fn particle(&mut self, kind: SplashParticle, position: Vec3, velocity: Vec3) -> Result<()> {
|
||||
self.player.events.push(MotionEvent::SplashParticle {
|
||||
bubble: matches!(kind, SplashParticle::Bubble),
|
||||
position,
|
||||
velocity,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn splash_event(&mut self) -> Result<()> {
|
||||
// The SPLASH game event: sculk listens to the player's moves itself.
|
||||
self.player.events.push(MotionEvent::SplashEvent);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*;
|
||||
* full death services remain controlled boundaries. Clock operations set up the
|
||||
* two damage-clock fields, not the complete enclosing native tick methods. */
|
||||
public final class VanillaSceneMotionOracle {
|
||||
static Field position,history,support,noBlocks,last,stuck,delay,trigger,attributeStorage,attributeDirty,attributeCached,impact,grace;
|
||||
static Field blockPositionField,position,history,support,noBlocks,last,stuck,delay,trigger,attributeStorage,attributeDirty,attributeCached,impact,grace;
|
||||
static MethodHandle aiStep;
|
||||
static Method refreshAttributes;
|
||||
static EntityDataAccessor<Float> healthKey,absorptionKey;
|
||||
@@ -71,6 +71,7 @@ public final class VanillaSceneMotionOracle {
|
||||
static String vectorBits(Vec3 p){return String.format("%016x,%016x,%016x",Double.doubleToLongBits(p.x),Double.doubleToLongBits(p.y),Double.doubleToLongBits(p.z));}
|
||||
static String soundName(SoundEvent s){
|
||||
if(s==SoundEvents.PLAYER_SMALL_FALL)return "small";if(s==SoundEvents.PLAYER_BIG_FALL)return "big";
|
||||
if(s==SoundEvents.PLAYER_SPLASH)return "splash";if(s==SoundEvents.PLAYER_SPLASH_HIGH_SPEED)return "splash-high";
|
||||
return VanillaBlockLandingOracle.sound(s);
|
||||
}
|
||||
static final class Sources extends DamageSources {
|
||||
@@ -107,6 +108,15 @@ public final class VanillaSceneMotionOracle {
|
||||
@Override public BlockGetter getChunkForCollisions(int x,int z){return chunks.get(key(x,z));}
|
||||
@Override public BlockState getBlockState(BlockPos p){var c=chunks.get(key(p.getX()>>4,p.getZ()>>4));return c==null?Blocks.AIR.defaultBlockState():c.getBlockState(p);}
|
||||
@Override public FluidState getFluidState(BlockPos p){return getBlockState(p).getFluidState();}
|
||||
// No dimension layers: FAST_LAVA keeps its default (the Overworld's slow lava).
|
||||
static final net.minecraft.world.attribute.EnvironmentAttributeSystem ATTRIBUTES=net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build();
|
||||
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes(){return ATTRIBUTES;}
|
||||
// EntityFluidInteraction.hasFluidAndLoaded: resident chunks only.
|
||||
@Override public net.minecraft.world.level.chunk.ChunkAccess getChunk(int x,int z,net.minecraft.world.level.chunk.status.ChunkStatus status,boolean load){return chunks.get(key(x,z));}
|
||||
// Entity.doWaterSplashEffect's particles (a client level adds them).
|
||||
@Override public void addParticle(net.minecraft.core.particles.ParticleOptions particle,double x,double y,double z,double xd,double yd,double zd){
|
||||
actor.events.add("splash-particle "+(particle==net.minecraft.core.particles.ParticleTypes.BUBBLE?"bubble":particle==net.minecraft.core.particles.ParticleTypes.SPLASH?"splash":"unknown")+" "+vectorBits(new Vec3(x,y,z))+" "+vectorBits(new Vec3(xd,yd,zd)));
|
||||
}
|
||||
@Override public List<VoxelShape> getEntityCollisions(Entity e,AABB b){return List.of();}
|
||||
@Override public List<Entity> getPushableEntities(Entity e,AABB b){return List.of();}
|
||||
@Override public List<Entity> getEntities(Entity e,AABB b){return e!=actor&&b.intersects(actor.getBoundingBox())?List.of(actor):List.of();}
|
||||
@@ -162,7 +172,7 @@ public final class VanillaSceneMotionOracle {
|
||||
@Override public CombatTracker getCombatTracker(){return tracker;}
|
||||
@Override public net.minecraft.server.PlayerAdvancements getAdvancements(){events.add("hurt-criterion");return advancements;}
|
||||
@Override public void onSyncedDataUpdated(EntityDataAccessor<?> key){if(key!=healthKey&&key!=absorptionKey)throw new AssertionError(key);events.add(String.format("updated %d %08x %s",key.id(),Float.floatToIntBits(getEntityData().get(key==healthKey?healthKey:absorptionKey)),getEntityData().isDirty()));}
|
||||
@Override public void gameEvent(Holder<GameEvent> event){if(event==GameEvent.ENTITY_DAMAGE)events.add("entity-damage");else super.gameEvent(event);}
|
||||
@Override public void gameEvent(Holder<GameEvent> event){if(event==GameEvent.ENTITY_DAMAGE)events.add("entity-damage");else if(event==GameEvent.SPLASH)events.add("splash-event");else super.gameEvent(event);}
|
||||
@Override public void die(DamageSource source){dead=true;events.add("death-request");}
|
||||
@Override protected void playHurtSound(DamageSource source){events.add("hurt-sound");}
|
||||
@Override protected SoundEvent getDeathSound(){return SoundEvents.PLAYER_DEATH;}
|
||||
@@ -171,20 +181,18 @@ public final class VanillaSceneMotionOracle {
|
||||
@Override public AttributeMap getAttributes(){return attrs;}
|
||||
@Override protected boolean getSharedFlag(int bit){return (flags&(1<<bit))!=0;}
|
||||
@Override protected void setSharedFlag(int bit,boolean v){flags=(byte)(v?flags|(1<<bit):flags&~(1<<bit));}
|
||||
@Override public void setPos(double x,double y,double z){write(position,this,new Vec3(x,y,z));setBoundingBox(EntityDimensions.scalable(getBbWidth(),getBbHeight()).makeBoundingBox(position()));}
|
||||
@Override public void setPos(double x,double y,double z){write(position,this,new Vec3(x,y,z));write(blockPositionField,this,BlockPos.containing(x,y,z));setBoundingBox(EntityDimensions.scalable(getBbWidth(),getBbHeight()).makeBoundingBox(position()));}
|
||||
@Override public BlockPos blockPosition(){return BlockPos.containing(position());}
|
||||
@Override public BlockState getInBlockState(){return level().getBlockState(blockPosition());}
|
||||
@Override public ItemStack getMainHandItem(){return ItemStack.EMPTY;}
|
||||
@Override public boolean isPassenger(){return statisticsFlags!=null&&statFlag(0);}
|
||||
@Override public boolean isSwimming(){return statisticsFlags!=null&&statFlag(1);}
|
||||
@Override public boolean isEyeInFluid(net.minecraft.tags.TagKey<net.minecraft.world.level.material.Fluid> tag){return statisticsFlags!=null&&statFlag(2);}
|
||||
@Override public boolean isInWater(){return statisticsFlags!=null&&statFlag(3);}
|
||||
@Override public boolean isEyeInFluid(net.minecraft.tags.TagKey<net.minecraft.world.level.material.Fluid> tag){return statisticsFlags!=null?statFlag(2):super.isEyeInFluid(tag);}
|
||||
@Override public boolean isInWater(){return statisticsFlags!=null?statFlag(3):super.isInWater();}
|
||||
@Override public boolean onClimbable(){return statisticsFlags!=null?statFlag(4):super.onClimbable();}
|
||||
@Override public boolean onGround(){return statisticsFlags!=null?statFlag(5):super.onGround();}
|
||||
@Override public boolean isSprinting(){return statisticsFlags!=null?statFlag(6):super.isSprinting();}
|
||||
@Override public boolean isCrouching(){return statisticsFlags!=null?statFlag(7):super.isCrouching();}
|
||||
@Override public boolean isInLava(){return false;}
|
||||
@Override public boolean isInLiquid(){return false;}
|
||||
@Override public boolean isFallFlying(){return statisticsFlags!=null&&statFlag(8);}
|
||||
@Override public boolean isAutoSpinAttack(){return false;}
|
||||
@Override public boolean isSpectator(){return false;}
|
||||
@@ -196,7 +204,6 @@ public final class VanillaSceneMotionOracle {
|
||||
@Override public MoveSimulationType getMoveSimulationType(){return MoveSimulationType.SERVER_AND_CLIENT;}
|
||||
@Override public boolean isClientAuthoritative(){return false;}
|
||||
@Override public void recordMovement(MoverType mover,Vec3 movement){}
|
||||
@Override protected boolean updateFluidInteraction(){return false;}
|
||||
@Override public void playSound(SoundEvent sound,float volume,float pitch){events.add(String.format("sound %s entity %08x %08x",soundName(sound),Float.floatToIntBits(volume),Float.floatToIntBits(pitch)));}
|
||||
@Override protected void playBlockFallSound(){events.add("block-fall-sound");}
|
||||
@Override public void awardStat(net.minecraft.stats.Stat<?> stat,int value){
|
||||
@@ -213,7 +220,6 @@ public final class VanillaSceneMotionOracle {
|
||||
@Override protected void playStepSound(BlockPos p,BlockState state){}
|
||||
@Override public void gameEvent(Holder<GameEvent> event,Entity source){}
|
||||
@Override public LivingEntity getControllingPassenger(){return null;}
|
||||
@Override public double getFluidHeight(net.minecraft.tags.TagKey<net.minecraft.world.level.material.Fluid> tag){return 0;}
|
||||
@Override public double getFluidJumpThreshold(){return .4;}
|
||||
// Block-inside effects and frozen ticks run only in "snow_tick" operations.
|
||||
boolean effects;int frozen;Vec3 tickStart;
|
||||
@@ -243,7 +249,12 @@ public final class VanillaSceneMotionOracle {
|
||||
}
|
||||
}
|
||||
void clock()throws Exception{sceneLevel.time++;tickCount++;if(cooldown.getInt(this)>0)cooldown.setInt(this,cooldown.getInt(this)-1);if(hurtTime>0)hurtTime--;}
|
||||
// Entity.baseTick's fluid phase: wasEyeInWater, the real
|
||||
// updateFluidInteraction, lava's fall halving and the first tick's end.
|
||||
void fluidTick(){wasEyeInWater=isEyeInFluid(net.minecraft.tags.FluidTags.WATER);updateFluidInteraction();if(isInLava())fallDistance*=0.5;firstTick=false;}
|
||||
String fluidState(){return wasTouchingWater+" "+wasEyeInWater+" "+isEyeInFluid(net.minecraft.tags.FluidTags.WATER)+" "+firstTick+String.format(" %016x %016x",Double.doubleToLongBits(getFluidHeight(net.minecraft.tags.FluidTags.WATER)),Double.doubleToLongBits(getFluidHeight(net.minecraft.tags.FluidTags.LAVA)));}
|
||||
void playerMovementTick(Vec3 input,boolean jumping){
|
||||
fluidTick();
|
||||
preparedInput=true;xxa=(float)input.x;yya=0;zza=(float)input.z;setJumping(jumping);
|
||||
try{aiStep();}finally{preparedInput=false;}
|
||||
}
|
||||
@@ -271,7 +282,7 @@ public final class VanillaSceneMotionOracle {
|
||||
out.printf("%s %s %s %s %s %s %s %016x %s %s %s %08x %d %08x %d %d %s | %s%n",p.horizontalCollision,p.verticalCollision,p.verticalCollisionBelow,p.minorHorizontalCollision,
|
||||
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)));
|
||||
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))+" fluid "+p.fluidState());
|
||||
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",
|
||||
@@ -285,8 +296,12 @@ public final class VanillaSceneMotionOracle {
|
||||
@SuppressWarnings("unchecked") public static void main(String[] args)throws Exception{
|
||||
net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]);
|
||||
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject());
|
||||
// The vanilla data pack's #water and #lava fluid tags.
|
||||
net.minecraft.core.registries.BuiltInRegistries.FLUID.prepareTagReload(new net.minecraft.tags.TagLoader.LoadResult<>(net.minecraft.core.registries.Registries.FLUID,Map.of(
|
||||
net.minecraft.tags.FluidTags.WATER,List.<Holder<net.minecraft.world.level.material.Fluid>>of(net.minecraft.world.level.material.Fluids.FLOWING_WATER.builtInRegistryHolder(),net.minecraft.world.level.material.Fluids.WATER.builtInRegistryHolder()),
|
||||
net.minecraft.tags.FluidTags.LAVA,List.<Holder<net.minecraft.world.level.material.Fluid>>of(net.minecraft.world.level.material.Fluids.FLOWING_LAVA.builtInRegistryHolder(),net.minecraft.world.level.material.Fluids.LAVA.builtInRegistryHolder())))).apply();
|
||||
var u=Class.forName("sun.misc.Unsafe");var f=u.getDeclaredField("theUnsafe");f.setAccessible(true);var unsafe=f.get(null);var allocate=u.getMethod("allocateInstance",Class.class);
|
||||
position=field(Entity.class,"position");history=field(Entity.class,"movementThisTick");support=field(Entity.class,"mainSupportingBlockPos");noBlocks=field(Entity.class,"onGroundNoBlocks");last=field(LivingEntity.class,"lastClimbablePos");stuck=field(Entity.class,"stuckSpeedMultiplier");
|
||||
position=field(Entity.class,"position");blockPositionField=field(Entity.class,"blockPosition");history=field(Entity.class,"movementThisTick");support=field(Entity.class,"mainSupportingBlockPos");noBlocks=field(Entity.class,"onGroundNoBlocks");last=field(LivingEntity.class,"lastClimbablePos");stuck=field(Entity.class,"stuckSpeedMultiplier");
|
||||
var abilities=field(Player.class,"abilities");
|
||||
healthKey=(EntityDataAccessor<Float>)field(LivingEntity.class,"DATA_HEALTH_ID").get(null);absorptionKey=(EntityDataAccessor<Float>)field(Player.class,"DATA_PLAYER_ABSORPTION_ID").get(null);
|
||||
healthDead=field(LivingEntity.class,"dead");cooldown=field(LivingEntity.class,"damageCooldownTime");lastHurt=field(LivingEntity.class,"lastHurt");noAction=field(LivingEntity.class,"noActionTime");lastDamage=field(LivingEntity.class,"lastDamageSource");lastStamp=field(LivingEntity.class,"lastDamageStamp");foodExhaustion=field(FoodData.class,"exhaustionLevel");foodTimer=field(FoodData.class,"tickTimer");
|
||||
@@ -320,6 +335,8 @@ public final class VanillaSceneMotionOracle {
|
||||
p.attrs=new TrackedAttributes(VanillaEntityAttributeOracle.supplier(EntityTypes.PLAYER));write(field(LivingEntity.class,"attributes"),p,p.attrs);
|
||||
write(field(Entity.class,"finalMovementsThisTick"),p,new ArrayList<>());write(field(Entity.class,"visitedBlocks"),p,new it.unimi.dsi.fastutil.longs.LongOpenHashSet());
|
||||
write(field(Entity.class,"insideEffectCollector"),p,new net.minecraft.world.entity.InsideBlockEffectApplier.StepBasedCollector());
|
||||
write(field(Entity.class,"fluidInteraction"),p,new net.minecraft.world.entity.EntityFluidInteraction(Set.of(net.minecraft.tags.FluidTags.WATER,net.minecraft.tags.FluidTags.LAVA)));
|
||||
write(field(Entity.class,"random"),p,level.rng);field(Entity.class,"firstTick").setBoolean(p,true);
|
||||
write(history,p,new ArrayDeque<>());write(support,p,Optional.empty());write(last,p,Optional.empty());write(stuck,p,Vec3.ZERO);write(abilities,p,new Abilities());
|
||||
write(field(ServerPlayer.class,"shoulderEntityLeft"),p,new net.minecraft.nbt.CompoundTag());write(field(ServerPlayer.class,"shoulderEntityRight"),p,new net.minecraft.nbt.CompoundTag());
|
||||
p.connection=(Connection)allocate.invoke(unsafe,Connection.class);
|
||||
@@ -366,6 +383,7 @@ public final class VanillaSceneMotionOracle {
|
||||
case "impulse"->p.setIgnoreFallDamageFromCurrentImpulse(op.get("ignore").getAsBoolean(),op.get("value").isJsonNull()?null:VanillaSceneCollisionOracle.vector(op.get("value")));
|
||||
case "block"->{var v=op.getAsJsonArray("position");var pos=new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt());var state=VanillaSceneCollisionOracle.state(op.get("name").getAsString());if(op.has("properties"))for(var property:op.getAsJsonObject("properties").entrySet())state=VanillaSceneCollisionOracle.property(state,state.getBlock().getStateDefinition().getProperty(property.getKey()),property.getValue().getAsString());level.chunks.get(key(pos.getX()>>4,pos.getZ()>>4)).write(pos,Block.getId(state));}
|
||||
case "landing"->{var v=op.getAsJsonArray("position");p.land(number(op.get("value")),op.get("ground").getAsBoolean(),new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt()));}
|
||||
case "fluid_tick"->p.fluidTick();
|
||||
case "travel"->p.travel(VanillaSceneCollisionOracle.vector(op.get("value")));
|
||||
case "tick"->p.movementTick(VanillaSceneCollisionOracle.vector(op.get("value")));
|
||||
case "player_tick"->p.playerMovementTick(VanillaSceneCollisionOracle.vector(op.get("value")),op.get("jumping").getAsBoolean());
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user