Merge pull request #187 from ludovic111/fix/arrow-water-127
Arrows get vanilla's water physics (#127)
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
//! Arrows over the client's resident scene (`arrows::tick`), for
|
||||
//! tools/test_arrow_parity.py: one line of state and one of events per operation.
|
||||
#![forbid(unsafe_code)]
|
||||
use horizon_client::{
|
||||
Result,
|
||||
arrows::{self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound},
|
||||
assets::Assets,
|
||||
blocks::BlockFacts,
|
||||
collisions,
|
||||
motion::{LAVA, MotionResources, WATER},
|
||||
projectiles::{Projectile, ProjectileKind},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufRead, Write},
|
||||
path::PathBuf,
|
||||
};
|
||||
fn number(v: &Value) -> f64 {
|
||||
f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())
|
||||
}
|
||||
fn vector(v: &Value) -> Vec3 {
|
||||
Vec3::new(number(&v[0]), number(&v[1]), number(&v[2]))
|
||||
}
|
||||
fn bits(v: Vec3) -> String {
|
||||
format!(
|
||||
"{:016x},{:016x},{:016x}",
|
||||
v.x.to_bits(),
|
||||
v.y.to_bits(),
|
||||
v.z.to_bits()
|
||||
)
|
||||
}
|
||||
fn seed(v: &Value) -> i64 {
|
||||
v.as_str().unwrap().parse().unwrap()
|
||||
}
|
||||
fn particle(k: ArrowParticle) -> &'static str {
|
||||
match k {
|
||||
ArrowParticle::Bubble => "bubble",
|
||||
ArrowParticle::Crit => "crit",
|
||||
ArrowParticle::Splash => "splash",
|
||||
}
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
if args.len() != 3 {
|
||||
return Err("usage: arrow_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into());
|
||||
}
|
||||
let root = PathBuf::from(&args[0]);
|
||||
let dir = PathBuf::from(&args[1]);
|
||||
let assets = Assets::load(&root)?;
|
||||
let mut scene = World::test_scene(&assets, 1)?;
|
||||
fs::write(
|
||||
dir.join("scene.json"),
|
||||
serde_json::to_vec(
|
||||
&serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":assets.model_gallery}),
|
||||
)?,
|
||||
)?;
|
||||
if args[2] == "--describe" {
|
||||
return Ok(());
|
||||
}
|
||||
let binding = collisions::load(&root, assets.registry)?;
|
||||
let motion = MotionResources::load(&root, &assets)?;
|
||||
let facts = BlockFacts::load(&root, assets.registry)?;
|
||||
let side = &args[2];
|
||||
let mut out = std::io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?);
|
||||
let mut level_random = LegacyRandom::new(0);
|
||||
for line in std::io::BufReader::new(fs::File::open(dir.join("inputs.txt"))?).lines() {
|
||||
let f: Value = serde_json::from_str(&line?)?;
|
||||
let kind = ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
critical: f["crit"].as_bool().unwrap(),
|
||||
effect: None,
|
||||
};
|
||||
let mut arrow = Projectile::new(kind, vector(&f["position"]), None)
|
||||
.with_arrow_random(LegacyRandom::new(seed(&f["seed"])));
|
||||
arrow.velocity = vector(&f["velocity"]);
|
||||
arrow.arrow.as_mut().unwrap().no_physics = f["no_physics"].as_bool().unwrap();
|
||||
for op in f["ops"].as_array().unwrap() {
|
||||
let mut events = Vec::new();
|
||||
match op["mode"].as_str().unwrap() {
|
||||
"tick" => {
|
||||
if !arrow.arrow.as_ref().unwrap().removed {
|
||||
let no_rain = |_| false;
|
||||
let view = ArrowScene {
|
||||
world: &scene,
|
||||
registry: assets.registry,
|
||||
facts: &facts,
|
||||
collision: &binding,
|
||||
fluids: &motion.fluids,
|
||||
raining: &no_rain,
|
||||
};
|
||||
arrows::tick(&mut arrow, &view, &[]);
|
||||
}
|
||||
for event in arrow.arrow.as_mut().unwrap().events.drain(..) {
|
||||
match event {
|
||||
ArrowEvent::Particle {
|
||||
kind,
|
||||
position,
|
||||
velocity,
|
||||
} => events.push(format!(
|
||||
"particle {} {} {}",
|
||||
particle(kind),
|
||||
bits(position),
|
||||
bits(velocity)
|
||||
)),
|
||||
ArrowEvent::Sound {
|
||||
sound,
|
||||
volume,
|
||||
pitch,
|
||||
} => events.push(format!(
|
||||
"sound {} {:08x} {:08x}",
|
||||
match sound {
|
||||
ArrowSound::HitGround => "hit",
|
||||
ArrowSound::Splash => "splash",
|
||||
ArrowSound::Extinguish => "extinguish",
|
||||
},
|
||||
volume.to_bits(),
|
||||
pitch.to_bits()
|
||||
)),
|
||||
ArrowEvent::BubbleColumnParticles { pos } => {
|
||||
for _ in 0..2 {
|
||||
let x = f64::from(pos.x) + level_random.next_double();
|
||||
let z = f64::from(pos.z) + level_random.next_double();
|
||||
let at = Vec3::new(x, f64::from(pos.y + 1), z);
|
||||
events.push(format!(
|
||||
"sent splash {} {} {:016x}",
|
||||
bits(at),
|
||||
bits(Vec3::ZERO),
|
||||
1.0f64.to_bits()
|
||||
));
|
||||
let x = f64::from(pos.x) + level_random.next_double();
|
||||
let z = f64::from(pos.z) + level_random.next_double();
|
||||
let at = Vec3::new(x, f64::from(pos.y + 1), z);
|
||||
events.push(format!(
|
||||
"sent bubble {} {} {:016x}",
|
||||
bits(at),
|
||||
bits(Vec3::new(0.0, 0.01, 0.0)),
|
||||
0.2f64.to_bits()
|
||||
));
|
||||
}
|
||||
}
|
||||
ArrowEvent::SplashEvent => events.push("splash-event".into()),
|
||||
ArrowEvent::ShootEvent => events.push("shoot-event".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
"block" => {
|
||||
let p = &op["position"];
|
||||
let mut state = assets
|
||||
.registry
|
||||
.default_state(op["name"].as_str().unwrap())
|
||||
.ok_or("missing fixture block")?;
|
||||
if let Some(properties) = op["properties"].as_object() {
|
||||
let mut definition = assets.registry.state(state).unwrap().clone();
|
||||
for (name, value) in properties {
|
||||
definition
|
||||
.properties
|
||||
.insert(name.clone(), value.as_str().unwrap().into());
|
||||
}
|
||||
state = assets
|
||||
.registry
|
||||
.id(&definition)
|
||||
.ok_or("missing fixture state")?;
|
||||
}
|
||||
scene.set(
|
||||
p[0].as_i64().unwrap() as i32,
|
||||
p[1].as_i64().unwrap() as i32,
|
||||
p[2].as_i64().unwrap() as i32,
|
||||
state,
|
||||
)?;
|
||||
}
|
||||
"velocity" => arrow.velocity = vector(&op["value"]),
|
||||
"level_seed" => level_random.set_seed(seed(&op["value"])),
|
||||
other => return Err(format!("unknown operation {other}").into()),
|
||||
}
|
||||
let a = arrow.arrow.as_ref().unwrap();
|
||||
writeln!(
|
||||
out,
|
||||
"arrow {} {} {:08x} {:08x} {} {} {} {} {} {} {} {} {} {:016x} {:016x} {} {} {:016x}",
|
||||
bits(arrow.position),
|
||||
bits(arrow.velocity),
|
||||
arrow.pitch.to_bits(),
|
||||
arrow.yaw.to_bits(),
|
||||
a.in_ground,
|
||||
a.in_ground_time,
|
||||
a.life,
|
||||
a.shake,
|
||||
a.last_state.map_or("none".into(), |s| s.0.to_string()),
|
||||
a.fire_ticks,
|
||||
a.was_touching_water,
|
||||
a.was_eye_in_water,
|
||||
a.first_tick,
|
||||
a.fluids.fluid_height(&Tags, WATER).to_bits(),
|
||||
a.fluids.fluid_height(&Tags, LAVA).to_bits(),
|
||||
a.removed,
|
||||
arrow.critical(),
|
||||
a.fall_distance.to_bits()
|
||||
)?;
|
||||
writeln!(out, "events {}", events.join(" | "))?;
|
||||
}
|
||||
writeln!(out, "end")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
struct Tags;
|
||||
impl horizon_world::entity_fluid::FluidMembership for Tags {
|
||||
fn fluid_in_tag(
|
||||
&self,
|
||||
kind: horizon_world::fluid::FluidKind,
|
||||
tag: horizon_world::entity_fluid::FluidTagId,
|
||||
) -> bool {
|
||||
use horizon_world::fluid::FluidKind;
|
||||
if tag == WATER {
|
||||
matches!(kind, FluidKind::Water | FluidKind::FlowingWater)
|
||||
} else {
|
||||
matches!(kind, FluidKind::Lava | FluidKind::FlowingLava)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,875 @@
|
||||
//! `AbstractArrow.tick` for arrows, tipped and spectral arrows: the flight with
|
||||
//! its water inertia and bubbles, the base tick's fluids (currents, splash),
|
||||
//! bubble columns and water along the path, sticking in blocks, falling out
|
||||
//! when the block goes, and despawning. Entity hits and their effects stay
|
||||
//! with the game (`projectile_hit`).
|
||||
use crate::{
|
||||
blocks::BlockFacts,
|
||||
collisions::SceneCollisions,
|
||||
mobs::Who,
|
||||
motion::{FluidResources, LAVA, WATER},
|
||||
projectiles::{Hit, Projectile},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Direction, Vec3, sweep_intersected_blocks},
|
||||
position::BlockPos,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::{
|
||||
block_collision::BlockCollisionRegistry,
|
||||
entity_fluid::{
|
||||
CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership,
|
||||
FluidSections, FluidTagId,
|
||||
},
|
||||
entity_fluid_tick::{self, EntityFluidTickWorld},
|
||||
fluid::{FluidHeightWorld, FluidKind, FluidState},
|
||||
fluid_flow::{FluidFlowWorld, flow_at},
|
||||
registry::BlockStateId,
|
||||
water_splash::{self, SplashParticle, WaterSplashWorld},
|
||||
};
|
||||
use std::{collections::HashSet, fmt};
|
||||
|
||||
/// `EntityType.ARROW` (and tipped/spectral arrows): 0.5 x 0.5, eyes at 0.13.
|
||||
const WIDTH: f32 = 0.5;
|
||||
const HEIGHT: f32 = 0.5;
|
||||
const EYE_HEIGHT: f32 = 0.13;
|
||||
|
||||
/// `AbstractArrow.Pickup`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Pickup {
|
||||
#[default]
|
||||
Disallowed,
|
||||
Allowed,
|
||||
CreativeOnly,
|
||||
}
|
||||
/// What an arrow's tick asks the game to play or show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ArrowEvent {
|
||||
/// `level().addParticle` (the client's copy of the arrow adds them).
|
||||
Particle {
|
||||
kind: ArrowParticle,
|
||||
position: Vec3,
|
||||
velocity: Vec3,
|
||||
},
|
||||
Sound {
|
||||
sound: ArrowSound,
|
||||
volume: f32,
|
||||
pitch: f32,
|
||||
},
|
||||
/// `Entity.sendBubbleColumnParticles` at this block: two SPLASH (speed 1)
|
||||
/// and two BUBBLE (spread 0, 0.01, 0, speed 0.2) particles at the top,
|
||||
/// placed by the level random (drawn by the consumer, nothing else draws
|
||||
/// it during an arrow's tick).
|
||||
BubbleColumnParticles {
|
||||
pos: BlockPos,
|
||||
},
|
||||
/// The SPLASH and PROJECTILE_SHOOT game events.
|
||||
SplashEvent,
|
||||
ShootEvent,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArrowParticle {
|
||||
Bubble,
|
||||
Crit,
|
||||
Splash,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArrowSound {
|
||||
/// `entity.generic.splash` (an arrow's splash and high-speed splash).
|
||||
Splash,
|
||||
/// The arrow's hit-ground sound (`entity.arrow.hit`).
|
||||
HitGround,
|
||||
/// `entity.generic.extinguish_fire`.
|
||||
Extinguish,
|
||||
}
|
||||
/// The arrow part of `AbstractArrow` and its `Entity` state.
|
||||
#[derive(Clone)]
|
||||
pub struct ArrowState {
|
||||
pub in_ground: bool,
|
||||
pub in_ground_time: i32,
|
||||
/// Ticks stuck (`life`): gone at 1200.
|
||||
pub life: i32,
|
||||
pub shake: i32,
|
||||
/// The block it stuck in (`lastState`).
|
||||
pub last_state: Option<BlockStateId>,
|
||||
pub pickup: Pickup,
|
||||
pub no_physics: bool,
|
||||
pub pierce: u8,
|
||||
/// `Entity.remainingFireTicks`.
|
||||
pub fire_ticks: i32,
|
||||
pub fall_distance: f64,
|
||||
pub fluids: EntityFluidInteraction,
|
||||
pub was_touching_water: bool,
|
||||
pub was_eye_in_water: bool,
|
||||
pub first_tick: bool,
|
||||
pub has_been_shot: bool,
|
||||
pub removed: bool,
|
||||
/// The arrow's own random (`Entity.random`).
|
||||
pub random: LegacyRandom,
|
||||
pub events: Vec<ArrowEvent>,
|
||||
}
|
||||
impl fmt::Debug for ArrowState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ArrowState")
|
||||
.field("in_ground", &self.in_ground)
|
||||
.field("life", &self.life)
|
||||
.field("fire_ticks", &self.fire_ticks)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
impl PartialEq for ArrowState {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.in_ground == other.in_ground
|
||||
&& self.life == other.life
|
||||
&& self.last_state == other.last_state
|
||||
&& self.fire_ticks == other.fire_ticks
|
||||
}
|
||||
}
|
||||
impl ArrowState {
|
||||
pub fn new(random: LegacyRandom) -> Self {
|
||||
Self {
|
||||
in_ground: false,
|
||||
in_ground_time: 0,
|
||||
life: 0,
|
||||
shake: 0,
|
||||
last_state: None,
|
||||
pickup: Pickup::Disallowed,
|
||||
no_physics: false,
|
||||
pierce: 0,
|
||||
fire_ticks: 0,
|
||||
fall_distance: 0.0,
|
||||
fluids: EntityFluidInteraction::new([WATER, LAVA]),
|
||||
was_touching_water: false,
|
||||
was_eye_in_water: false,
|
||||
first_tick: true,
|
||||
has_been_shot: false,
|
||||
removed: false,
|
||||
random,
|
||||
events: Vec::new(),
|
||||
}
|
||||
}
|
||||
/// `Entity.isOnFire` (arrows are not fire immune).
|
||||
pub fn on_fire(&self) -> bool {
|
||||
self.fire_ticks > 0
|
||||
}
|
||||
/// `Entity.clearFire`.
|
||||
pub fn clear_fire(&mut self) {
|
||||
self.fire_ticks = self.fire_ticks.min(0);
|
||||
}
|
||||
}
|
||||
/// The blocks, fluids and weather an arrow flies through.
|
||||
pub struct ArrowScene<'a, 'r> {
|
||||
pub world: &'a World,
|
||||
pub registry: &'a horizon_world::registry::BlockRegistry,
|
||||
pub facts: &'a BlockFacts,
|
||||
pub collision: &'a BlockCollisionRegistry<'r>,
|
||||
pub fluids: &'a FluidResources,
|
||||
/// `Level.isRainingAt`.
|
||||
pub raining: &'a dyn Fn(BlockPos) -> bool,
|
||||
}
|
||||
impl ArrowScene<'_, '_> {
|
||||
fn block(&self, p: BlockPos) -> BlockStateId {
|
||||
self.world.block(p.x, p.y, p.z)
|
||||
}
|
||||
fn is_air(&self, state: BlockStateId) -> bool {
|
||||
self.facts.is_air(state)
|
||||
}
|
||||
/// `BlockState.getCollisionShape(level, pos)` (an empty collision context).
|
||||
fn collision_boxes(&self, state: BlockStateId, p: BlockPos) -> Vec<Aabb> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
subject: None,
|
||||
};
|
||||
self.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.map(|s| s.boxes().to_vec())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
fn property(&self, state: BlockStateId, name: &str) -> Option<&str> {
|
||||
self.registry
|
||||
.state(state)?
|
||||
.properties
|
||||
.get(name)
|
||||
.map(String::as_str)
|
||||
}
|
||||
/// `ClipContext.Block.COLLIDER` with `Fluid.NONE`: the first block hit.
|
||||
fn clip(&self, from: Vec3, to: Vec3) -> Option<(Vec3, BlockPos, [i32; 3])> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
subject: None,
|
||||
};
|
||||
let hit = horizon_core::geometry::traverse_blocks(from, to, 1024, |p: BlockPos| {
|
||||
let state = self.block(p);
|
||||
if self.is_air(state) {
|
||||
return None;
|
||||
}
|
||||
let shape = self
|
||||
.collision
|
||||
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
|
||||
.ok()?;
|
||||
shape.clip(from, to, p)
|
||||
});
|
||||
let hit = hit.ok().flatten()?;
|
||||
Some((hit.location, hit.block, hit.direction.normal()))
|
||||
}
|
||||
/// `CollisionGetter.noCollision(null, box)` over blocks.
|
||||
fn no_block_collision(&self, b: Aabb) -> bool {
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
for x in (lo.x.floor() as i32 - 1)..=(hi.x.floor() as i32 + 1) {
|
||||
for y in (lo.y.floor() as i32 - 1)..=(hi.y.floor() as i32 + 1) {
|
||||
for z in (lo.z.floor() as i32 - 1)..=(hi.z.floor() as i32 + 1) {
|
||||
let p = BlockPos::new(x, y, z);
|
||||
let state = self.block(p);
|
||||
if self.is_air(state) {
|
||||
continue;
|
||||
}
|
||||
let origin = Vec3::new(f64::from(x), f64::from(y), f64::from(z));
|
||||
if self
|
||||
.collision_boxes(state, p)
|
||||
.iter()
|
||||
.any(|c| c.move_by(origin).intersects(b))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
fn bounds(at: Vec3) -> Aabb {
|
||||
// EntityDimensions.makeBoundingBox: half the float width.
|
||||
let w = f64::from(WIDTH / 2.0);
|
||||
Aabb::new(
|
||||
Vec3::new(at.x - w, at.y, at.z - w),
|
||||
Vec3::new(at.x + w, at.y + f64::from(HEIGHT), at.z + w),
|
||||
)
|
||||
}
|
||||
/// `Projectile.lerpRotation`.
|
||||
fn lerp_rotation(mut old: f32, new: f32) -> f32 {
|
||||
while new - old < -180.0 {
|
||||
old -= 360.0;
|
||||
}
|
||||
while new - old >= 180.0 {
|
||||
old += 360.0;
|
||||
}
|
||||
old + 0.2 * (new - old)
|
||||
}
|
||||
/// `(float)(Mth.atan2(y, x) * 180.0F / (float)Math.PI)`: compiled as one
|
||||
/// multiplication by the folded float constant.
|
||||
fn degrees(y: f64, x: f64) -> f32 {
|
||||
horizon_core::geometry::trig::atan2_degrees(y, x)
|
||||
}
|
||||
fn signum(v: f64) -> f64 {
|
||||
if v > 0.0 {
|
||||
1.0
|
||||
} else if v < 0.0 {
|
||||
-1.0
|
||||
} else {
|
||||
v
|
||||
}
|
||||
}
|
||||
/// One arrow tick: whether to keep it and what it hit.
|
||||
pub fn tick(p: &mut Projectile, scene: &ArrowScene, targets: &[(Who, Aabb)]) -> (bool, Hit) {
|
||||
let Some(mut st) = p.arrow.take() else {
|
||||
return (false, Hit::None);
|
||||
};
|
||||
let hit = Ticker {
|
||||
p,
|
||||
st: &mut st,
|
||||
scene,
|
||||
}
|
||||
.tick(targets);
|
||||
p.stuck = st.in_ground;
|
||||
let keep = !st.removed;
|
||||
p.arrow = Some(st);
|
||||
(keep, hit)
|
||||
}
|
||||
struct Ticker<'p, 's, 'a, 'r> {
|
||||
p: &'p mut Projectile,
|
||||
st: &'s mut ArrowState,
|
||||
scene: &'s ArrowScene<'a, 'r>,
|
||||
}
|
||||
impl Ticker<'_, '_, '_, '_> {
|
||||
fn position(&self) -> Vec3 {
|
||||
self.p.position
|
||||
}
|
||||
fn block_position(&self) -> BlockPos {
|
||||
BlockPos::containing(self.p.position)
|
||||
}
|
||||
/// `Entity.isInRain`: at the block position or the top of the box.
|
||||
fn in_rain(&self) -> bool {
|
||||
let p = self.block_position();
|
||||
(self.scene.raining)(p)
|
||||
|| (self.scene.raining)(BlockPos::new(
|
||||
p.x,
|
||||
bounds(self.p.position).max_position().y.floor() as i32,
|
||||
p.z,
|
||||
))
|
||||
}
|
||||
fn tick(&mut self, targets: &[(Who, Aabb)]) -> Hit {
|
||||
let physics = !self.st.no_physics;
|
||||
let movement = self.p.velocity;
|
||||
let block_pos = self.block_position();
|
||||
let state = self.scene.block(block_pos);
|
||||
if !self.scene.is_air(state) && physics {
|
||||
let origin = Vec3::new(
|
||||
f64::from(block_pos.x),
|
||||
f64::from(block_pos.y),
|
||||
f64::from(block_pos.z),
|
||||
);
|
||||
let at = self.position();
|
||||
if self
|
||||
.scene
|
||||
.collision_boxes(state, block_pos)
|
||||
.iter()
|
||||
.any(|b| b.move_by(origin).contains(at))
|
||||
{
|
||||
self.p.velocity = Vec3::ZERO;
|
||||
self.st.in_ground = true;
|
||||
}
|
||||
}
|
||||
if self.st.shake > 0 {
|
||||
self.st.shake -= 1;
|
||||
}
|
||||
if self.st.was_touching_water || self.in_rain() {
|
||||
self.st.clear_fire();
|
||||
}
|
||||
if self.st.in_ground && physics {
|
||||
if self.st.last_state != Some(state) && self.should_fall() {
|
||||
self.start_falling();
|
||||
} else {
|
||||
// AbstractArrow.tickDespawn.
|
||||
self.st.life += 1;
|
||||
if self.st.life >= 1200 {
|
||||
self.st.removed = true;
|
||||
}
|
||||
}
|
||||
self.st.in_ground_time += 1;
|
||||
if !self.st.removed {
|
||||
let at = self.position();
|
||||
self.apply_effects_from_blocks(at, at);
|
||||
}
|
||||
return Hit::None;
|
||||
}
|
||||
self.st.in_ground_time = 0;
|
||||
let original = self.position();
|
||||
if self.st.was_touching_water {
|
||||
// getWaterInertia, then the bubbles behind it.
|
||||
self.p.velocity = self.p.velocity.scale(f64::from(0.6f32));
|
||||
let v = self.p.velocity;
|
||||
for _ in 0..4 {
|
||||
self.st.events.push(ArrowEvent::Particle {
|
||||
kind: ArrowParticle::Bubble,
|
||||
position: Vec3::new(
|
||||
original.x - v.x * 0.25,
|
||||
original.y - v.y * 0.25,
|
||||
original.z - v.z * 0.25,
|
||||
),
|
||||
velocity: v,
|
||||
});
|
||||
}
|
||||
}
|
||||
if self.p.critical() {
|
||||
for i in 0..4 {
|
||||
let f = f64::from(i) / 4.0;
|
||||
self.st.events.push(ArrowEvent::Particle {
|
||||
kind: ArrowParticle::Crit,
|
||||
position: Vec3::new(
|
||||
original.x + movement.x * f,
|
||||
original.y + movement.y * f,
|
||||
original.z + movement.z * f,
|
||||
),
|
||||
velocity: Vec3::new(-movement.x, -movement.y + 0.2, -movement.z),
|
||||
});
|
||||
}
|
||||
}
|
||||
let y_rot = if physics {
|
||||
degrees(movement.x, movement.z)
|
||||
} else {
|
||||
degrees(-movement.x, -movement.z)
|
||||
};
|
||||
let x_rot = degrees(movement.y, movement.horizontal_distance());
|
||||
self.p.pitch = lerp_rotation(self.p.pitch, x_rot);
|
||||
self.p.yaw = lerp_rotation(self.p.yaw, y_rot);
|
||||
self.check_left_owner(targets);
|
||||
let mut hit = Hit::None;
|
||||
let end = Vec3::new(
|
||||
original.x + movement.x,
|
||||
original.y + movement.y,
|
||||
original.z + movement.z,
|
||||
);
|
||||
if physics {
|
||||
hit = self.step_move_and_hit(original, end, targets);
|
||||
} else {
|
||||
self.p.position = end;
|
||||
self.apply_effects_from_blocks(original, end);
|
||||
}
|
||||
if !self.st.was_touching_water {
|
||||
self.p.velocity = self.p.velocity.scale(f64::from(0.99f32));
|
||||
}
|
||||
if physics && !self.st.in_ground {
|
||||
// Entity.applyGravity: AbstractArrow.getDefaultGravity.
|
||||
self.add_velocity(-0.05);
|
||||
}
|
||||
// Projectile.tick, then Entity.baseTick's fluid and fire phases.
|
||||
if !self.st.has_been_shot {
|
||||
self.st.events.push(ArrowEvent::ShootEvent);
|
||||
self.st.has_been_shot = true;
|
||||
}
|
||||
self.st.was_eye_in_water = self.st.fluids.is_eye_in_fluid(&Tags, WATER);
|
||||
let mut fluids = std::mem::take(&mut self.st.fluids);
|
||||
let _ = entity_fluid_tick::update(&mut fluids, self, WATER, LAVA, 1_000_000);
|
||||
self.st.fluids = fluids;
|
||||
if self.st.fire_ticks > 0 {
|
||||
self.st.fire_ticks -= 1;
|
||||
}
|
||||
if !self.st.first_tick && self.st.fluids.is_in_fluid(&Tags, LAVA) {
|
||||
self.st.fall_distance *= 0.5;
|
||||
}
|
||||
if self.position().y < f64::from(crate::chunk::MIN_Y - 64) {
|
||||
self.st.removed = true;
|
||||
}
|
||||
self.st.first_tick = false;
|
||||
hit
|
||||
}
|
||||
/// `getDeltaMovement().add(0, y, 0)`: the zeros added to x and z also
|
||||
/// turn a negative zero positive.
|
||||
fn add_velocity(&mut self, y: f64) {
|
||||
let v = self.p.velocity;
|
||||
self.p.velocity = Vec3::new(v.x + 0.0, v.y + y, v.z + 0.0);
|
||||
}
|
||||
/// `Projectile.checkLeftOwner`: out of the owner's box once the arrow's
|
||||
/// box, swept by its motion and grown by 1, no longer touches it.
|
||||
fn check_left_owner(&mut self, targets: &[(Who, Aabb)]) {
|
||||
if self.p.left_owner {
|
||||
return;
|
||||
}
|
||||
let owner = targets
|
||||
.iter()
|
||||
.find(|(who, _)| Some(*who) == self.p.owner)
|
||||
.map(|(_, b)| *b);
|
||||
let swept = bounds(self.p.position)
|
||||
.expand_towards(self.p.velocity)
|
||||
.inflate(Vec3::new(1.0, 1.0, 1.0));
|
||||
self.p.left_owner = owner.is_none_or(|b| !swept.intersects(b));
|
||||
}
|
||||
/// `AbstractArrow.shouldFall`.
|
||||
fn should_fall(&self) -> bool {
|
||||
let at = self.position();
|
||||
self.st.in_ground
|
||||
&& self
|
||||
.scene
|
||||
.no_block_collision(Aabb::new(at, at).inflate(Vec3::new(0.06, 0.06, 0.06)))
|
||||
}
|
||||
/// `AbstractArrow.startFalling`.
|
||||
fn start_falling(&mut self) {
|
||||
self.st.in_ground = false;
|
||||
let v = self.p.velocity;
|
||||
let x = f64::from(self.st.random.next_float() * 0.2);
|
||||
let y = f64::from(self.st.random.next_float() * 0.2);
|
||||
let z = f64::from(self.st.random.next_float() * 0.2);
|
||||
self.p.velocity = Vec3::new(v.x * x, v.y * y, v.z * z);
|
||||
self.st.life = 0;
|
||||
}
|
||||
/// `AbstractArrow.stepMoveAndHit`: the nearest entity on the way, else the
|
||||
/// block (not piercing: the game removes an arrow that hits an entity).
|
||||
fn step_move_and_hit(&mut self, from: Vec3, to: Vec3, targets: &[(Who, Aabb)]) -> Hit {
|
||||
let block = self.scene.clip(from, to);
|
||||
let end = block.map_or(to, |b| b.0);
|
||||
let mut best: Option<(Who, Vec3, f64)> = None;
|
||||
for (who, b) in targets {
|
||||
if Some(*who) == self.p.owner && !self.p.left_owner {
|
||||
continue;
|
||||
}
|
||||
if let Some(at) = b.inflate(Vec3::new(0.3, 0.3, 0.3)).clip(from, end) {
|
||||
let c = b.center();
|
||||
let d = from.distance_squared(Vec3::new(c.x, b.min_position().y, c.z));
|
||||
if best.is_none_or(|bb| d < bb.2) {
|
||||
best = Some((*who, at, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
let next = best.map_or(end, |b| b.1);
|
||||
self.p.position = next;
|
||||
self.apply_effects_from_blocks(from, next);
|
||||
if let Some((who, at, _)) = best {
|
||||
// The game hurts it; the arrow is spent (piercing is not modelled).
|
||||
self.st.removed = true;
|
||||
return Hit::Entity { who, at };
|
||||
}
|
||||
let Some((at, pos, face)) = block else {
|
||||
return Hit::None;
|
||||
};
|
||||
if self.st.removed {
|
||||
return Hit::None;
|
||||
}
|
||||
let state = self.scene.block(pos);
|
||||
if self.scene.is_air(state) {
|
||||
return Hit::None;
|
||||
}
|
||||
self.on_hit_block(pos, state);
|
||||
Hit::Block {
|
||||
pos: [pos.x, pos.y, pos.z],
|
||||
at,
|
||||
face,
|
||||
}
|
||||
}
|
||||
/// `AbstractArrow.onHitBlock`: back off the face by 0.05 along each axis
|
||||
/// it moved on, stop, and stick.
|
||||
fn on_hit_block(&mut self, _pos: BlockPos, state: BlockStateId) {
|
||||
self.st.last_state = Some(state);
|
||||
let v = self.p.velocity;
|
||||
let offset = f64::from(0.05f32);
|
||||
self.p.position = Vec3::new(
|
||||
self.p.position.x - signum(v.x) * offset,
|
||||
self.p.position.y - signum(v.y) * offset,
|
||||
self.p.position.z - signum(v.z) * offset,
|
||||
);
|
||||
self.p.velocity = Vec3::ZERO;
|
||||
let pitch = 1.2 / (self.st.random.next_float() * 0.2 + 0.9);
|
||||
self.st.events.push(ArrowEvent::Sound {
|
||||
sound: ArrowSound::HitGround,
|
||||
volume: 1.0,
|
||||
pitch,
|
||||
});
|
||||
self.st.in_ground = true;
|
||||
self.st.shake = 7;
|
||||
self.p.set_critical(false);
|
||||
self.st.pierce = 0;
|
||||
}
|
||||
/// `Entity.applyEffectsFromBlocks(from, to)` for an arrow: the blocks and
|
||||
/// fluids its box passes through (bubble columns push, water puts the fire
|
||||
/// out), then rain.
|
||||
fn apply_effects_from_blocks(&mut self, from: Vec3, to: Vec3) {
|
||||
// Entity.isAffectedByBlocks.
|
||||
if self.st.removed || self.st.no_physics {
|
||||
return;
|
||||
}
|
||||
let was_on_fire = self.st.on_fire();
|
||||
let previous_fire = self.st.fire_ticks;
|
||||
let mut visited = HashSet::new();
|
||||
let mut extinguish = false;
|
||||
let used = self.check_inside_blocks(from, to, &mut visited, &mut extinguish, 16);
|
||||
if 16 - used <= 0 {
|
||||
self.check_inside_blocks(to, to, &mut visited, &mut extinguish, 1);
|
||||
}
|
||||
// StepBasedCollector.applyAndClear: EXTINGUISH.
|
||||
if extinguish && !self.st.removed {
|
||||
self.st.clear_fire();
|
||||
}
|
||||
if self.in_rain() {
|
||||
self.st.clear_fire();
|
||||
}
|
||||
if was_on_fire && !self.st.on_fire() {
|
||||
// Entity.playEntityOnFireExtinguishedSound.
|
||||
let pitch = 1.6 + (self.st.random.next_float() - self.st.random.next_float()) * 0.4;
|
||||
self.st.events.push(ArrowEvent::Sound {
|
||||
sound: ArrowSound::Extinguish,
|
||||
volume: 0.7,
|
||||
pitch,
|
||||
});
|
||||
}
|
||||
let ignited = self.st.fire_ticks > previous_fire;
|
||||
if !self.st.on_fire() && !ignited {
|
||||
// -getFireImmuneTicks(): 0 for arrows.
|
||||
self.st.fire_ticks = 0;
|
||||
}
|
||||
}
|
||||
/// `Entity.checkInsideBlocks(from, to, ...)`: returns the iterations used.
|
||||
fn check_inside_blocks(
|
||||
&mut self,
|
||||
from: Vec3,
|
||||
to: Vec3,
|
||||
visited: &mut HashSet<BlockPos>,
|
||||
extinguish: &mut bool,
|
||||
max_iterations: i32,
|
||||
) -> i32 {
|
||||
let deflated = bounds(to).deflate(Vec3::new(
|
||||
f64::from(1.0e-5f32),
|
||||
f64::from(1.0e-5f32),
|
||||
f64::from(1.0e-5f32),
|
||||
));
|
||||
let far = from.distance_squared(to) > 0.999_990_000_000_252_6f64 * 0.999_990_000_000_252_6;
|
||||
let mut hits = Vec::new();
|
||||
let mut iterations = 0;
|
||||
let alive = !self.st.removed;
|
||||
let _ = sweep_intersected_blocks(from, to, deflated, 1_000_000, |p, iteration| {
|
||||
if !alive || iteration >= max_iterations {
|
||||
return false;
|
||||
}
|
||||
iterations = iteration;
|
||||
hits.push((p, iteration));
|
||||
true
|
||||
});
|
||||
for (p, _) in hits {
|
||||
let state = self.scene.block(p);
|
||||
if self.scene.is_air(state) {
|
||||
continue;
|
||||
}
|
||||
// getEntityInsideCollisionShape: the whole block for these.
|
||||
let inside_block = true;
|
||||
let fluid = self.scene.fluids.fluid(state);
|
||||
let inside_fluid = self.collided_with_fluid(fluid, p, from, to);
|
||||
if !(inside_block || inside_fluid) || !visited.insert(p) {
|
||||
continue;
|
||||
}
|
||||
if &*self.scene.facts.get(state).name == "minecraft:bubble_column" {
|
||||
let precise = far
|
||||
|| deflated.intersects(Aabb::new(
|
||||
Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)),
|
||||
Vec3::new(f64::from(p.x + 1), f64::from(p.y + 1), f64::from(p.z + 1)),
|
||||
));
|
||||
if precise {
|
||||
self.bubble_column(state, p);
|
||||
}
|
||||
}
|
||||
if inside_fluid && matches!(fluid.kind(), FluidKind::Water | FluidKind::FlowingWater) {
|
||||
*extinguish = true;
|
||||
}
|
||||
}
|
||||
iterations + 1
|
||||
}
|
||||
/// `Entity.collidedWithFluid`: the fluid's box swept from `from` to `to`.
|
||||
fn collided_with_fluid(
|
||||
&mut self,
|
||||
fluid: FluidState,
|
||||
p: BlockPos,
|
||||
from: Vec3,
|
||||
to: Vec3,
|
||||
) -> bool {
|
||||
if fluid.kind() == FluidKind::Empty {
|
||||
return false;
|
||||
}
|
||||
let Ok(height) = fluid.height_at(self, [p.x, p.y, p.z]) else {
|
||||
return false;
|
||||
};
|
||||
let b = Aabb::new(
|
||||
Vec3::new(f64::from(p.x), f64::from(p.y), f64::from(p.z)),
|
||||
Vec3::new(
|
||||
f64::from(p.x) + 1.0,
|
||||
f64::from(p.y) + f64::from(height),
|
||||
f64::from(p.z) + 1.0,
|
||||
),
|
||||
);
|
||||
bounds(from).collided_along_vector(to.subtract(from), &[b])
|
||||
}
|
||||
/// `BubbleColumnBlock.entityInside` with `Projectile`'s pushes.
|
||||
fn bubble_column(&mut self, state: BlockStateId, p: BlockPos) {
|
||||
let drag = self.scene.property(state, "drag") == Some("true");
|
||||
let above = self.scene.block(BlockPos::new(p.x, p.y + 1, p.z));
|
||||
// The state above's collision shape, queried at this position.
|
||||
let nothing_above = self.scene.collision_boxes(above, p).is_empty()
|
||||
&& self.scene.fluids.fluid(above).kind() == FluidKind::Empty;
|
||||
if self.st.in_ground {
|
||||
return;
|
||||
}
|
||||
if nothing_above {
|
||||
self.add_velocity(if drag { -0.03 } else { 0.1 });
|
||||
self.st
|
||||
.events
|
||||
.push(ArrowEvent::BubbleColumnParticles { pos: p });
|
||||
} else {
|
||||
self.add_velocity(if drag { -0.03 } else { 0.06 });
|
||||
self.st.fall_distance = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Tags;
|
||||
impl FluidMembership for Tags {
|
||||
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
|
||||
if tag == WATER {
|
||||
matches!(kind, FluidKind::Water | FluidKind::FlowingWater)
|
||||
} else {
|
||||
matches!(kind, FluidKind::Lava | FluidKind::FlowingLava)
|
||||
}
|
||||
}
|
||||
}
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
impl FluidMembership for Ticker<'_, '_, '_, '_> {
|
||||
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
|
||||
Tags.fluid_in_tag(kind, tag)
|
||||
}
|
||||
}
|
||||
impl CurrentTarget for Ticker<'_, '_, '_, '_> {
|
||||
type Error = Error;
|
||||
fn is_player_class(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn velocity(&mut self) -> Result<Vec3, Error> {
|
||||
Ok(self.p.velocity)
|
||||
}
|
||||
fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Error> {
|
||||
let v = self.p.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.p.velocity = sum;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl FluidInteractionWorld for Ticker<'_, '_, '_, '_> {
|
||||
type Error = Error;
|
||||
type Chunk = ();
|
||||
fn interaction_box(&mut self) -> Result<Option<Aabb>, Error> {
|
||||
Ok(Some(
|
||||
bounds(self.p.position).deflate(Vec3::new(0.001, 0.001, 0.001)),
|
||||
))
|
||||
}
|
||||
fn loaded_chunk(&mut self, x: i32, z: i32) -> Result<Option<()>, Error> {
|
||||
Ok(self.scene.world.chunks.contains_key(&(x, z)).then_some(()))
|
||||
}
|
||||
fn chunk_sections(&mut self, _: ()) -> Result<FluidSections<'_>, 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.p.position.y
|
||||
}
|
||||
fn block_x(&self) -> i32 {
|
||||
self.p.position.x.floor() as i32
|
||||
}
|
||||
fn eye_y(&mut self) -> Result<f64, Error> {
|
||||
Ok(self.p.position.y + f64::from(EYE_HEIGHT))
|
||||
}
|
||||
fn block_z(&self) -> i32 {
|
||||
self.p.position.z.floor() as i32
|
||||
}
|
||||
fn fluid_state(&mut self, p: BlockPos) -> Result<FluidState, Error> {
|
||||
Ok(self.scene.fluids.fluid(self.scene.block(p)))
|
||||
}
|
||||
fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32, Error> {
|
||||
f.height_at(self, [p.x, p.y, p.z])
|
||||
}
|
||||
fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32, Error> {
|
||||
f.camera_height_at(self, [p.x, p.y, p.z])
|
||||
}
|
||||
fn flow(&mut self, f: FluidState, p: BlockPos) -> Result<Vec3, Error> {
|
||||
flow_at(self, f, p)
|
||||
}
|
||||
}
|
||||
impl EntityFluidTickWorld for Ticker<'_, '_, '_, '_> {
|
||||
/// `AbstractArrow.isPushedByFluid`: not when stuck.
|
||||
fn is_pushed_by_fluid(&mut self) -> Result<bool, Error> {
|
||||
Ok(!self.st.in_ground)
|
||||
}
|
||||
fn reset_fall_distance(&mut self) -> Result<(), Error> {
|
||||
self.st.fall_distance = 0.0;
|
||||
Ok(())
|
||||
}
|
||||
fn was_touching_water(&self) -> bool {
|
||||
self.st.was_touching_water
|
||||
}
|
||||
fn first_tick(&self) -> bool {
|
||||
self.st.first_tick
|
||||
}
|
||||
fn water_splash(&mut self) -> Result<(), Error> {
|
||||
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.st.was_touching_water = value;
|
||||
}
|
||||
fn fast_lava(&mut self) -> Result<bool, Error> {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
impl FluidHeightWorld for Ticker<'_, '_, '_, '_> {
|
||||
type Error = Error;
|
||||
fn fluid(&mut self, p: [i32; 3]) -> Result<FluidState, Error> {
|
||||
Ok(self
|
||||
.scene
|
||||
.fluids
|
||||
.fluid(self.scene.block(BlockPos::new(p[0], p[1], p[2]))))
|
||||
}
|
||||
fn sturdy_down(&mut self, p: [i32; 3]) -> Result<bool, Error> {
|
||||
let state = self.scene.block(BlockPos::new(p[0], p[1], p[2]));
|
||||
Ok(self.scene.fluids.sturdy(state, Direction::Down))
|
||||
}
|
||||
}
|
||||
impl FluidFlowWorld for Ticker<'_, '_, '_, '_> {
|
||||
type Error = Error;
|
||||
type Block = BlockStateId;
|
||||
fn fluid(&mut self, p: BlockPos) -> Result<FluidState, Error> {
|
||||
Ok(self.scene.fluids.fluid(self.scene.block(p)))
|
||||
}
|
||||
fn block(&mut self, p: BlockPos) -> Result<BlockStateId, Error> {
|
||||
Ok(self.scene.block(p))
|
||||
}
|
||||
fn blocks_fluid_flow(&self, s: BlockStateId) -> bool {
|
||||
self.scene.fluids.blocks_flow(s)
|
||||
}
|
||||
fn is_ice_class(&self, s: BlockStateId) -> bool {
|
||||
self.scene.fluids.ice(s)
|
||||
}
|
||||
fn is_face_sturdy(
|
||||
&mut self,
|
||||
s: BlockStateId,
|
||||
_: BlockPos,
|
||||
d: Direction,
|
||||
) -> Result<bool, Error> {
|
||||
Ok(self.scene.fluids.sturdy(s, d))
|
||||
}
|
||||
}
|
||||
/// `Entity.doWaterSplashEffect` with the arrow's own random.
|
||||
impl WaterSplashWorld for Ticker<'_, '_, '_, '_> {
|
||||
type Error = Error;
|
||||
type Entity = ();
|
||||
type Sound = ();
|
||||
fn this_entity(&self) {}
|
||||
fn controlling_passenger(&mut self) -> Result<Option<()>, Error> {
|
||||
Ok(None)
|
||||
}
|
||||
fn velocity(&mut self, _: ()) -> Result<Vec3, Error> {
|
||||
Ok(self.p.velocity)
|
||||
}
|
||||
fn splash_sound(&mut self, _: bool) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
fn random_float(&mut self) -> Result<f32, Error> {
|
||||
Ok(self.st.random.next_float())
|
||||
}
|
||||
fn random_double(&mut self) -> Result<f64, Error> {
|
||||
Ok(self.st.random.next_double())
|
||||
}
|
||||
fn play_sound(&mut self, _: (), volume: f32, pitch: f32) -> Result<(), Error> {
|
||||
self.st.events.push(ArrowEvent::Sound {
|
||||
sound: ArrowSound::Splash,
|
||||
volume,
|
||||
pitch,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn position(&self) -> Vec3 {
|
||||
self.p.position
|
||||
}
|
||||
fn width(&self) -> f32 {
|
||||
WIDTH
|
||||
}
|
||||
fn particle(
|
||||
&mut self,
|
||||
kind: SplashParticle,
|
||||
position: Vec3,
|
||||
velocity: Vec3,
|
||||
) -> Result<(), Error> {
|
||||
self.st.events.push(ArrowEvent::Particle {
|
||||
kind: match kind {
|
||||
SplashParticle::Bubble => ArrowParticle::Bubble,
|
||||
SplashParticle::Splash => ArrowParticle::Splash,
|
||||
},
|
||||
position,
|
||||
velocity,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn splash_event(&mut self) -> Result<(), Error> {
|
||||
self.st.events.push(ArrowEvent::SplashEvent);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1360,6 +1360,7 @@ impl Game<'_> {
|
||||
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
|
||||
let mut hits = Vec::new();
|
||||
let mut deflections: Vec<[f64; 3]> = Vec::new();
|
||||
let mut arrow_events = Vec::new();
|
||||
{
|
||||
let mut targets: Vec<(Who, Aabb)> = self
|
||||
.mobs
|
||||
@@ -1392,9 +1393,28 @@ impl Game<'_> {
|
||||
self.world.random.next_float()
|
||||
};
|
||||
let w = self.mob_world_base(&[]);
|
||||
// Level.isRainingAt: raining, open to the sky (the biome's
|
||||
// precipitation is not checked here).
|
||||
let (raining, world) = (w.raining, w.world);
|
||||
let rain = move |p: BlockPos| raining && world.light(p.x, p.y, p.z) >> 4 == 15;
|
||||
let scene = horizon_client::arrows::ArrowScene {
|
||||
world: w.world,
|
||||
registry: w.registry,
|
||||
facts: w.facts,
|
||||
collision: w.collision,
|
||||
fluids: &self.motion.fluids,
|
||||
raining: &rain,
|
||||
};
|
||||
let pw = ProjWorld { w: &w, targets };
|
||||
projectiles.retain_mut(|p| {
|
||||
let (keep, hit) = p.tick(&pw);
|
||||
let (keep, hit) = if p.arrow.is_some() {
|
||||
horizon_client::arrows::tick(p, &scene, &pw.targets)
|
||||
} else {
|
||||
p.tick(&pw)
|
||||
};
|
||||
if let Some(a) = p.arrow.as_mut() {
|
||||
arrow_events.extend(a.events.drain(..).map(|e| (p.position, e)));
|
||||
}
|
||||
let wind = matches!(
|
||||
p.kind,
|
||||
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge
|
||||
@@ -1408,6 +1428,9 @@ impl Game<'_> {
|
||||
&& breezes.contains(&id)
|
||||
{
|
||||
super::wind::reverse(p, jitter);
|
||||
if let Some(a) = p.arrow.as_mut() {
|
||||
a.removed = false;
|
||||
}
|
||||
deflections.push([at.x, at.y, at.z]);
|
||||
return true;
|
||||
}
|
||||
@@ -1433,12 +1456,83 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:entity.breeze.deflect", Some(at), 1.0, 1.0);
|
||||
}
|
||||
for (at, event) in arrow_events {
|
||||
self.arrow_event(at, event);
|
||||
}
|
||||
self.creatures.projectiles.append(&mut projectiles);
|
||||
for (p, hit) in hits {
|
||||
self.projectile_hit(&p, hit)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// What an arrow's tick asked for: its particles and sounds.
|
||||
fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) {
|
||||
use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound};
|
||||
use horizon_client::particles::{ParticleOptions, ParticleType};
|
||||
let kind = |k| match k {
|
||||
ArrowParticle::Bubble => ParticleType::Bubble,
|
||||
ArrowParticle::Crit => ParticleType::Crit,
|
||||
ArrowParticle::Splash => ParticleType::Splash,
|
||||
};
|
||||
match event {
|
||||
ArrowEvent::Particle {
|
||||
kind: k,
|
||||
position,
|
||||
velocity,
|
||||
} => self.particles.add(
|
||||
&ParticleOptions::simple(kind(k)),
|
||||
[position.x, position.y, position.z],
|
||||
[velocity.x, velocity.y, velocity.z],
|
||||
),
|
||||
ArrowEvent::Sound {
|
||||
sound,
|
||||
volume,
|
||||
pitch,
|
||||
} => {
|
||||
let name = match sound {
|
||||
ArrowSound::Splash => "minecraft:entity.generic.splash",
|
||||
ArrowSound::HitGround => "minecraft:entity.arrow.hit",
|
||||
ArrowSound::Extinguish => "minecraft:entity.generic.extinguish_fire",
|
||||
};
|
||||
self.audio
|
||||
.play(name, Some([at.x, at.y, at.z]), volume, pitch);
|
||||
}
|
||||
ArrowEvent::BubbleColumnParticles { pos } => {
|
||||
// Entity.sendBubbleColumnParticles: the level random places them.
|
||||
for _ in 0..2 {
|
||||
let r = &mut self.world.random;
|
||||
let splash = [
|
||||
f64::from(pos.x) + r.next_double(),
|
||||
f64::from(pos.y + 1),
|
||||
f64::from(pos.z) + r.next_double(),
|
||||
];
|
||||
let bubble = [
|
||||
f64::from(pos.x) + r.next_double(),
|
||||
f64::from(pos.y + 1),
|
||||
f64::from(pos.z) + r.next_double(),
|
||||
];
|
||||
self.particles.send_particles(
|
||||
&ParticleOptions::simple(ParticleType::Splash),
|
||||
splash,
|
||||
[0.0; 3],
|
||||
1.0,
|
||||
1,
|
||||
);
|
||||
self.particles.send_particles(
|
||||
&ParticleOptions::simple(ParticleType::Bubble),
|
||||
bubble,
|
||||
[0.0, 0.01, 0.0],
|
||||
0.2,
|
||||
1,
|
||||
);
|
||||
}
|
||||
}
|
||||
ArrowEvent::SplashEvent => {
|
||||
self.projectile_event("minecraft:splash", None, [at.x, at.y, at.z]);
|
||||
}
|
||||
ArrowEvent::ShootEvent => {}
|
||||
}
|
||||
}
|
||||
fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
|
||||
self.combat.projectile_owner = match p.owner {
|
||||
Some(Who::Mob(id)) => Some(id),
|
||||
@@ -1530,13 +1624,8 @@ impl Game<'_> {
|
||||
self.audio.play(sound, Some(atp), volume, pitch);
|
||||
}
|
||||
}
|
||||
(ProjectileKind::Arrow { .. }, Hit::Block { .. }) => {
|
||||
if let Some((sound, volume, pitch)) =
|
||||
arrow_impact_sound(&mut self.world.random, true)
|
||||
{
|
||||
self.audio.play(sound, Some(atp), volume, pitch);
|
||||
}
|
||||
}
|
||||
// AbstractArrow.onHitBlock plays its sound itself (ArrowEvent).
|
||||
(ProjectileKind::Arrow { .. }, Hit::Block { .. }) => {}
|
||||
(ProjectileKind::Snowball, hit) => {
|
||||
if let Hit::Entity {
|
||||
who: Who::Mob(id), ..
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
pub mod advancements;
|
||||
pub mod ambience;
|
||||
pub mod animate_tick;
|
||||
pub mod arrows;
|
||||
pub mod assets;
|
||||
pub mod atlas_sources;
|
||||
pub mod attack_strength;
|
||||
|
||||
@@ -54,11 +54,23 @@ impl FluidResources {
|
||||
pub fn fluid(&self, state: BlockStateId) -> FluidState {
|
||||
self.states.get(state).unwrap_or(FluidState::EMPTY)
|
||||
}
|
||||
fn sturdy(&self, state: BlockStateId, d: Direction) -> bool {
|
||||
/// `BlockState.isFaceSturdy(FULL)` on that face.
|
||||
pub 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)
|
||||
}
|
||||
/// `#minecraft:blocks_fluid_flow` membership.
|
||||
pub fn blocks_flow(&self, state: BlockStateId) -> bool {
|
||||
self.blocks_flow
|
||||
.get(state.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
}
|
||||
/// `IceBlock` or one of its subclasses.
|
||||
pub fn ice(&self, state: BlockStateId) -> bool {
|
||||
self.ice.get(state.0 as usize).copied().unwrap_or(false)
|
||||
}
|
||||
}
|
||||
/// The player's `EntityFluidInteraction` and the water flags around it.
|
||||
pub struct PlayerFluids {
|
||||
@@ -262,20 +274,10 @@ impl FluidFlowWorld for MotionWorld<'_, '_, '_> {
|
||||
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)
|
||||
self.resources.fluids.blocks_flow(s)
|
||||
}
|
||||
fn is_ice_class(&self, s: BlockStateId) -> bool {
|
||||
self.resources
|
||||
.fluids
|
||||
.ice
|
||||
.get(s.0 as usize)
|
||||
.copied()
|
||||
.unwrap_or(false)
|
||||
self.resources.fluids.ice(s)
|
||||
}
|
||||
fn is_face_sturdy(&mut self, s: BlockStateId, _: BlockPos, d: Direction) -> Result<bool> {
|
||||
Ok(self.resources.fluids.sturdy(s, d))
|
||||
|
||||
@@ -76,6 +76,8 @@ pub struct Projectile {
|
||||
pub left_owner: bool,
|
||||
/// The shooter's bow enchantments (Power, Punch, Flame, Piercing).
|
||||
pub bonus: crate::mobs::gear::ArrowBonus,
|
||||
/// Arrows' `AbstractArrow` state (ticked by `arrows::tick`).
|
||||
pub arrow: Option<Box<crate::arrows::ArrowState>>,
|
||||
}
|
||||
/// What a projectile struck this tick.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -124,6 +126,7 @@ fn axis_of(d: u8) -> u8 {
|
||||
}
|
||||
impl Projectile {
|
||||
pub fn new(kind: ProjectileKind, position: Vec3, owner: Option<Who>) -> Self {
|
||||
let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. });
|
||||
Self {
|
||||
kind,
|
||||
owner,
|
||||
@@ -136,6 +139,30 @@ impl Projectile {
|
||||
stuck: false,
|
||||
left_owner: false,
|
||||
bonus: Default::default(),
|
||||
arrow: kind_is_arrow.then(|| {
|
||||
// Entity.random: seeded unpredictably, the position stands in.
|
||||
Box::new(crate::arrows::ArrowState::new(
|
||||
horizon_core::random::LegacyRandom::new(
|
||||
position.x.to_bits() as i64 ^ position.z.to_bits().rotate_left(17) as i64,
|
||||
),
|
||||
))
|
||||
}),
|
||||
}
|
||||
}
|
||||
/// The arrow's own random from now on (`Entity.random`).
|
||||
pub fn with_arrow_random(mut self, random: horizon_core::random::LegacyRandom) -> Self {
|
||||
if let Some(a) = self.arrow.as_mut() {
|
||||
a.random = random;
|
||||
}
|
||||
self
|
||||
}
|
||||
/// `AbstractArrow.isCritArrow`.
|
||||
pub fn critical(&self) -> bool {
|
||||
matches!(self.kind, ProjectileKind::Arrow { critical: true, .. })
|
||||
}
|
||||
pub fn set_critical(&mut self, value: bool) {
|
||||
if let ProjectileKind::Arrow { critical, .. } = &mut self.kind {
|
||||
*critical = value;
|
||||
}
|
||||
}
|
||||
pub fn is_arrow(&self) -> bool {
|
||||
@@ -478,10 +505,6 @@ impl Projectile {
|
||||
if matches!(self.kind, ProjectileKind::ShulkerBullet { .. }) {
|
||||
return self.tick_bullet(w);
|
||||
}
|
||||
if self.stuck {
|
||||
// AbstractArrow despawns 1200 ticks after sticking.
|
||||
return (self.age < 1200, Hit::None);
|
||||
}
|
||||
let water = w.in_water(self.position);
|
||||
match self.kind {
|
||||
ProjectileKind::SmallFireball
|
||||
@@ -501,6 +524,7 @@ impl Projectile {
|
||||
(v.z + v.z / len * 0.1) * inertia,
|
||||
);
|
||||
}
|
||||
// Arrows tick with `arrows::tick`.
|
||||
ProjectileKind::Arrow { .. } => {}
|
||||
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge => {}
|
||||
// LlamaSpit.tick: gone in water; drag and gravity follow the move.
|
||||
@@ -558,19 +582,6 @@ impl Projectile {
|
||||
}
|
||||
if let Some((at, pos, face)) = block {
|
||||
self.position = at;
|
||||
if self.is_arrow() {
|
||||
// AbstractArrow.onHitBlock: stick, nudged back out of the face.
|
||||
let v = self.velocity;
|
||||
let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9);
|
||||
self.position = Vec3::new(
|
||||
at.x - v.x / len * 0.05,
|
||||
at.y - v.y / len * 0.05,
|
||||
at.z - v.z / len * 0.05,
|
||||
);
|
||||
self.stuck = true;
|
||||
self.age = 0;
|
||||
return (true, Hit::Block { pos, at, face });
|
||||
}
|
||||
return (false, Hit::Block { pos, at, face });
|
||||
}
|
||||
if self.kind == ProjectileKind::LlamaSpit {
|
||||
@@ -600,16 +611,7 @@ impl Projectile {
|
||||
return (self.position.y > -128.0 && self.age < 6000, Hit::None);
|
||||
}
|
||||
self.position = to;
|
||||
if self.is_arrow() {
|
||||
// AbstractArrow.tick: inertia 0.99 (0.6 in water) after moving, then gravity.
|
||||
let inertia = if water { 0.6 } else { 0.99 };
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x * inertia,
|
||||
self.velocity.y * inertia - self.gravity(),
|
||||
self.velocity.z * inertia,
|
||||
);
|
||||
self.update_rotation();
|
||||
} else if !self.is_fireball() {
|
||||
if !self.is_fireball() {
|
||||
self.update_rotation();
|
||||
}
|
||||
let alive =
|
||||
@@ -702,7 +704,7 @@ mod tests {
|
||||
assert!((p.velocity.y + 0.06).abs() < 1e-9);
|
||||
}
|
||||
#[test]
|
||||
fn arrow_applies_drag_then_gravity_after_moving() {
|
||||
fn arrow_damage_is_speed_times_base() {
|
||||
let mut p = Projectile::new(
|
||||
ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
@@ -713,35 +715,6 @@ mod tests {
|
||||
None,
|
||||
);
|
||||
p.velocity = Vec3::new(3.0, 0.0, 0.0);
|
||||
let w = Empty(vec![]);
|
||||
p.tick(&w);
|
||||
assert!((p.position.x - 3.0).abs() < 1e-9);
|
||||
assert!((p.velocity.x - 2.97).abs() < 1e-9);
|
||||
assert!((p.velocity.y + 0.05).abs() < 1e-9);
|
||||
}
|
||||
#[test]
|
||||
fn arrow_hits_entity_box_inflated_by_margin() {
|
||||
let target = Aabb::new(Vec3::new(2.0, 99.0, -0.3), Vec3::new(2.6, 100.8, 0.3));
|
||||
let mut p = Projectile::new(
|
||||
ProjectileKind::Arrow {
|
||||
base_damage: 2.0,
|
||||
critical: false,
|
||||
effect: None,
|
||||
},
|
||||
Vec3::new(0.0, 100.0, 0.0),
|
||||
None,
|
||||
);
|
||||
p.velocity = Vec3::new(3.0, 0.0, 0.0);
|
||||
let w = Empty(vec![(Who::Mob(7), target)]);
|
||||
let (keep, hit) = p.tick(&w);
|
||||
assert!(!keep);
|
||||
assert!(matches!(
|
||||
hit,
|
||||
Hit::Entity {
|
||||
who: Who::Mob(7),
|
||||
..
|
||||
}
|
||||
));
|
||||
let mut r = LegacyRandom::new(1);
|
||||
// ceil(3 * 2) = 6 for a non-critical arrow.
|
||||
assert_eq!(p.arrow_damage(&mut r), 6.0);
|
||||
|
||||
@@ -157,7 +157,7 @@ pub fn has_fluid_and_loaded<W: FluidInteractionWorld>(
|
||||
}
|
||||
Ok(present)
|
||||
}
|
||||
#[derive(Default)]
|
||||
#[derive(Clone, Default)]
|
||||
pub struct EntityFluidInteraction {
|
||||
trackers: Vec<FluidTracker>,
|
||||
currents: Vec<(FluidTagId, CurrentAccumulator)>,
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package dev.horizonlab.parity;
|
||||
import com.google.gson.*;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.sounds.*;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
|
||||
import net.minecraft.world.entity.projectile.arrow.Arrow;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.level.*;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.border.WorldBorder;
|
||||
import net.minecraft.world.level.gameevent.GameEvent;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.phys.*;
|
||||
import net.minecraft.world.phys.shapes.*;
|
||||
import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*;
|
||||
|
||||
/** Real arrows (`Arrow`, through `AbstractArrow.tick`) over an independently
|
||||
* built copy of the development client's resident scene: flight, water inertia
|
||||
* and bubbles, fluid currents and splashes, bubble columns, sticking in blocks,
|
||||
* falling out when the block goes, and despawning. No entities to hit, no rain,
|
||||
* no owner; sounds, particles and game events are recorded in order. */
|
||||
public final class VanillaArrowOracle {
|
||||
static final class Border extends WorldBorder {
|
||||
@Override public boolean isInsideCloseToBorder(Entity e,AABB b){return false;}
|
||||
}
|
||||
static String bits(Vec3 v){return String.format("%016x,%016x,%016x",Double.doubleToLongBits(v.x),Double.doubleToLongBits(v.y),Double.doubleToLongBits(v.z));}
|
||||
static String sound(SoundEvent s){
|
||||
if(s==SoundEvents.ARROW_HIT)return "hit";if(s==SoundEvents.GENERIC_SPLASH)return "splash";if(s==SoundEvents.GENERIC_EXTINGUISH_FIRE)return "extinguish";
|
||||
throw new AssertionError("unexpected sound "+s);
|
||||
}
|
||||
static String particle(net.minecraft.core.particles.ParticleOptions p){
|
||||
if(p==net.minecraft.core.particles.ParticleTypes.BUBBLE)return "bubble";if(p==net.minecraft.core.particles.ParticleTypes.CRIT)return "crit";
|
||||
if(p==net.minecraft.core.particles.ParticleTypes.SPLASH)return "splash";
|
||||
throw new AssertionError("unexpected particle "+p);
|
||||
}
|
||||
static final class Level extends net.minecraft.server.level.ServerLevel {
|
||||
Map<Long,Chunk> chunks;WorldBorder border;net.minecraft.util.RandomSource rng;List<String> events;net.minecraft.server.MinecraftServer server;
|
||||
static final net.minecraft.world.attribute.EnvironmentAttributeSystem ATTRIBUTES=net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build();
|
||||
Level(){super(null,null,null,null,null,null,false,0L,List.of(),false);}
|
||||
@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes(){return ATTRIBUTES;}
|
||||
@Override public boolean isClientSide(){return false;}
|
||||
@Override public int getNextEntityId(){return 1;}
|
||||
@Override public int getMinY(){return -64;}
|
||||
@Override public BlockGetter getChunkForCollisions(int x,int z){return chunks.get(key(x,z));}
|
||||
@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));}
|
||||
@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();}
|
||||
@Override public List<VoxelShape> getEntityCollisions(Entity e,AABB b){return List.of();}
|
||||
@Override public List<Entity> getEntities(Entity e,AABB b,java.util.function.Predicate<? super Entity> p){return List.of();}
|
||||
@Override public WorldBorder getWorldBorder(){return border;}
|
||||
@Override public net.minecraft.util.RandomSource getRandom(){return rng;}
|
||||
@Override public boolean isRainingAt(BlockPos p){return false;}
|
||||
@Override public net.minecraft.server.MinecraftServer getServer(){return server;}
|
||||
@Override public void gameEvent(Holder<GameEvent> event,Vec3 pos,GameEvent.Context context){
|
||||
if(event==GameEvent.PROJECTILE_SHOOT)events.add("shoot-event");else if(event==GameEvent.SPLASH)events.add("splash-event");else throw new AssertionError(event);
|
||||
}
|
||||
// Projectile.onHit's PROJECTILE_LAND: the game posts it from the hit it is handed.
|
||||
@Override public void gameEvent(Holder<GameEvent> event,BlockPos pos,GameEvent.Context context){if(event!=GameEvent.PROJECTILE_LAND)throw new AssertionError(event);}
|
||||
@Override public void playSound(Entity except,double x,double y,double z,SoundEvent s,SoundSource source,float volume,float pitch){
|
||||
events.add(String.format("sound %s %08x %08x",sound(s),Float.floatToIntBits(volume),Float.floatToIntBits(pitch)));
|
||||
}
|
||||
@Override public void addParticle(net.minecraft.core.particles.ParticleOptions p,double x,double y,double z,double xd,double yd,double zd){
|
||||
events.add("particle "+particle(p)+" "+bits(new Vec3(x,y,z))+" "+bits(new Vec3(xd,yd,zd)));
|
||||
}
|
||||
@Override public <T extends net.minecraft.core.particles.ParticleOptions> int sendParticles(T p,double x,double y,double z,int count,double dx,double dy,double dz,double speed){
|
||||
if(count!=1)throw new AssertionError(count);
|
||||
events.add("sent "+particle(p)+" "+bits(new Vec3(x,y,z))+" "+bits(new Vec3(dx,dy,dz))+String.format(" %016x",Double.doubleToLongBits(speed)));return 0;
|
||||
}
|
||||
}
|
||||
static Field field(Class<?> c,String n)throws Exception{var f=c.getDeclaredField(n);f.setAccessible(true);return f;}
|
||||
static long seed(JsonElement v){return Long.parseLong(v.getAsString());}
|
||||
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();
|
||||
// The arrow's pickup stack: an arrow item without data components.
|
||||
Items.ARROW.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY);
|
||||
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);
|
||||
var description=JsonParser.parseString(Files.readString(dir.resolve("scene.json"))).getAsJsonObject();
|
||||
var trace=new Trace();trace.out=new PrintWriter(OutputStream.nullOutputStream());trace.fail=-1;
|
||||
var level=(Level)allocate.invoke(unsafe,Level.class);level.chunks=VanillaSceneCollisionOracle.scene(description,trace);level.border=new Border();
|
||||
level.rng=net.minecraft.util.RandomSource.create(0);level.events=new ArrayList<>();
|
||||
var server=(VanillaBlockLandingOracle.Server)allocate.invoke(unsafe,VanillaBlockLandingOracle.Server.class);
|
||||
server.d=new VanillaBlockLandingOracle.Data();server.d.out=new PrintWriter(OutputStream.nullOutputStream());server.d.f=JsonParser.parseString("{\"fail\":-1,\"protected\":false}").getAsJsonObject();level.server=server;
|
||||
field(net.minecraft.server.MinecraftServer.class,"debugSubscribers").set(server,new net.minecraft.util.debug.ServerDebugSubscribers(server));
|
||||
var random=field(Entity.class,"random");var inGroundTime=field(AbstractArrow.class,"inGroundTime");var life=field(AbstractArrow.class,"life");var lastState=field(AbstractArrow.class,"lastState");
|
||||
var touching=field(Entity.class,"wasTouchingWater");var eyes=field(Entity.class,"wasEyeInWater");var first=field(Entity.class,"firstTick");
|
||||
var inGround=AbstractArrow.class.getDeclaredMethod("isInGround");inGround.setAccessible(true);
|
||||
try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var lines=Files.lines(dir.resolve("inputs.txt"))){
|
||||
for(var line:(Iterable<String>)lines::iterator){
|
||||
var row=JsonParser.parseString(line).getAsJsonObject();
|
||||
var a=new Arrow(level,0,0,0,new ItemStack(Items.ARROW),null);
|
||||
random.set(a,net.minecraft.util.RandomSource.create(seed(row.get("seed"))));
|
||||
a.setPos(VanillaSceneCollisionOracle.vector(row.get("position")));a.setDeltaMovement(VanillaSceneCollisionOracle.vector(row.get("velocity")));
|
||||
a.setCritArrow(row.get("crit").getAsBoolean());a.setNoPhysics(row.get("no_physics").getAsBoolean());
|
||||
for(var value:row.getAsJsonArray("ops")){
|
||||
var op=value.getAsJsonObject();
|
||||
switch(op.get("mode").getAsString()){
|
||||
// ServerLevel.tickNonPassenger: old position, tick count, tick.
|
||||
case "tick"->{if(!a.isRemoved()){a.setOldPosAndRot();a.tickCount++;a.tick();}}
|
||||
case "block"->{
|
||||
var v=op.getAsJsonArray("position");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());
|
||||
VanillaSceneCollisionOracle.put(level.chunks,v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt(),state);
|
||||
}
|
||||
case "velocity"->a.setDeltaMovement(VanillaSceneCollisionOracle.vector(op.get("value")));
|
||||
case "level_seed"->level.rng.setSeed(seed(op.get("value")));
|
||||
default->throw new AssertionError(op);
|
||||
}
|
||||
var state=(BlockState)lastState.get(a);
|
||||
out.printf("arrow %s %s %08x %08x %s %d %d %d %s %d %s %s %s %016x %016x %s %s %016x%n",bits(a.position()),bits(a.getDeltaMovement()),Float.floatToIntBits(a.getXRot()),Float.floatToIntBits(a.getYRot()),
|
||||
inGround.invoke(a),inGroundTime.getInt(a),life.getInt(a),a.shakeTime,state==null?"none":Block.getId(state),a.getRemainingFireTicks(),touching.getBoolean(a),eyes.getBoolean(a),first.getBoolean(a),
|
||||
Double.doubleToLongBits(a.getFluidHeight(net.minecraft.tags.FluidTags.WATER)),Double.doubleToLongBits(a.getFluidHeight(net.minecraft.tags.FluidTags.LAVA)),a.isRemoved(),a.isCritArrow(),Double.doubleToLongBits(a.fallDistance));
|
||||
out.println("events "+String.join(" | ",level.events));level.events.clear();
|
||||
}
|
||||
out.println("end");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare arrows (AbstractArrow.tick) over the native client's resident scene.
|
||||
|
||||
Real vanilla `Arrow` entities tick in an independently built copy of the
|
||||
scene (`VanillaArrowOracle`, client and server jars); Horizon's
|
||||
`arrows::tick` runs over the scene itself (`examples/arrow_probe.rs`). Every
|
||||
operation prints the arrow's position, motion, rotation, ground state, life,
|
||||
shake, stuck block, fire ticks, water flags, fluid heights, removal, crit flag
|
||||
and fall distance by exact bits, then its sounds, particles and game events in
|
||||
order. Cases: flights in the air with and without crits or physics, into and
|
||||
through water (inertia, bubbles, splashes, currents of flowing water, eyes),
|
||||
kelp, seagrass and waterlogged blocks, bubble columns with and without drag
|
||||
and with air or water above, sticking in full and partial blocks, falling out
|
||||
when the block goes, starting inside a block, and despawning after 1200 ticks.
|
||||
No entities, owner, rain, lava or fire.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import struct
|
||||
import subprocess
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_native_client as client
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
import test_native_client as client
|
||||
|
||||
|
||||
def bits(value): return struct.pack('>d', value).hex()
|
||||
def vec(values): return list(map(bits, values))
|
||||
def op(mode, value=None, **extra): return dict(mode=mode, value=value, **extra)
|
||||
|
||||
|
||||
def corpus():
|
||||
rng = random.Random(0x4152524f57)
|
||||
def place(name, positions, properties=None):
|
||||
return [op('block', name='minecraft:' + name, position=list(p), **({'properties': properties} if properties else {})) for p in positions]
|
||||
def restore(positions):
|
||||
return [op('block', name='minecraft:air', position=list(p)) for p in positions]
|
||||
def arrow(position, velocity, ops, crit=False, no_physics=False):
|
||||
return dict(seed=str(rng.randrange(-1 << 63, 1 << 63)), position=vec(position), velocity=vec(velocity),
|
||||
crit=crit, no_physics=no_physics, ops=[op('level_seed', str(rng.randrange(1 << 48)))] + ops)
|
||||
ticks = lambda n: [op('tick') for _ in range(n)]
|
||||
def aim(speed, yaw, pitch):
|
||||
import math
|
||||
y, p = math.radians(yaw), math.radians(pitch)
|
||||
return (-math.sin(y) * math.cos(p) * speed, -math.sin(p) * speed, math.cos(y) * math.cos(p) * speed)
|
||||
# Flights in the air onto the floor (y 4), sticking, then resting.
|
||||
for _ in range(40):
|
||||
start = (rng.uniform(17, 30), rng.uniform(5, 14), rng.uniform(2, 30))
|
||||
v = aim(rng.choice([.3, 1, 1.6, 2.4, 3]), rng.uniform(-180, 180), rng.uniform(-60, 45))
|
||||
yield arrow(start, v, ticks(60), crit=rng.random() < .5)
|
||||
# Without physics: straight through blocks, no gravity, inverted yaw.
|
||||
for _ in range(6):
|
||||
start = (rng.uniform(17, 30), rng.uniform(5, 8), rng.uniform(2, 30))
|
||||
yield arrow(start, aim(1.5, rng.uniform(-180, 180), rng.uniform(-30, 30)), ticks(25), no_physics=True)
|
||||
# Water: a pool three deep, shot into from above, through it and from inside.
|
||||
pool = [(x, y, z) for x in range(20, 29) for y in range(4, 7) for z in range(20, 29)]
|
||||
for level in ['0', '0', '0', '2', '6', '8']:
|
||||
for _ in range(8):
|
||||
start = rng.choice([(rng.uniform(20, 29), rng.uniform(8, 14), rng.uniform(16, 19)),
|
||||
(rng.uniform(21, 28), rng.uniform(4.2, 6.5), rng.uniform(21, 28))])
|
||||
v = aim(rng.choice([.05, .4, 1.2, 2.5, 3]), rng.uniform(-60, 60), rng.uniform(-50, 20))
|
||||
ops = place('water', pool, {'level': level}) + ticks(70) + restore(pool)
|
||||
yield arrow(start, v, ops, crit=rng.random() < .3)
|
||||
# Currents: random flowing water around a slow arrow.
|
||||
for _ in range(16):
|
||||
cells = [(x, 4, z) for x in range(21, 28) for z in range(21, 28)]
|
||||
ops = [op('block', name='minecraft:water', position=list(c), properties={'level': rng.choice(['0', '1', '3', '5', '7', '9'])}) for c in cells]
|
||||
ops += ticks(40) + restore(cells)
|
||||
yield arrow((rng.uniform(21.3, 27.7), rng.uniform(4.05, 4.6), rng.uniform(21.3, 27.7)), aim(rng.choice([0, .01, .2]), rng.uniform(-180, 180), 0), ops)
|
||||
# Kelp, seagrass and waterlogged blocks are water too.
|
||||
for name, properties in [('kelp', {'age': '5'}), ('kelp_plant', {}), ('seagrass', {}), ('oak_slab', {'type': 'bottom', 'waterlogged': 'true'}),
|
||||
('oak_fence', {'waterlogged': 'true'}), ('iron_bars', {'waterlogged': 'true'})]:
|
||||
blocks = [(x, y, z) for x in range(22, 27) for y in range(4, 6) for z in range(22, 27)]
|
||||
for _ in range(4):
|
||||
v = aim(rng.choice([.6, 1.5, 2.8]), rng.uniform(-40, 40), rng.uniform(5, 60))
|
||||
ops = place(name, blocks, properties) + ticks(50) + restore(blocks)
|
||||
yield arrow((rng.uniform(22, 27), rng.uniform(7, 10), rng.uniform(18, 20)), v, ops)
|
||||
# Bubble columns: up or down, open above or under water.
|
||||
for drag in ['true', 'false']:
|
||||
for roof in [None, 'water', 'stone']:
|
||||
column = [(24, y, 24) for y in range(4, 9)]
|
||||
ops = place('bubble_column', column, {'drag': drag})
|
||||
if roof:
|
||||
ops += place(roof, [(24, 9, 24)])
|
||||
for start, v in [((24.5, 12, 24.5), (0, -.3, 0)), ((24.5, 4.2, 24.5), (0, .4, 0)), ((24.2, 6, 24.7), (.02, 0, -.01)), ((22, 9, 24.5), (.5, -.2, 0))]:
|
||||
yield arrow(start, v, ops + ticks(60) + restore(column + [(24, 9, 24)]))
|
||||
# Sticking in partial blocks, then the block goes (or changes) under it.
|
||||
shapes = [('stone', {}), ('oak_slab', {'type': 'top'}), ('oak_slab', {'type': 'bottom'}), ('oak_stairs', {'facing': 'east'}),
|
||||
('oak_fence', {}), ('glass_pane', {'north': 'true', 'south': 'true'}), ('oak_trapdoor', {'half': 'top'}),
|
||||
('lantern', {}), ('iron_chain', {'axis': 'y'}), ('white_carpet', {}), ('snow', {'layers': '3'}), ('anvil', {'facing': 'north'})]
|
||||
for name, properties in shapes:
|
||||
for after in ['air', 'glass', None]:
|
||||
target = [(25, 9, 25)]
|
||||
v = rng.choice([(0, -1.2, 0), (.9, .1, 0), (0, .1, -.9), (.7, -.7, .2)])
|
||||
start = (25.5 - v[0] * 3, 9.5 - v[1] * 3, 25.5 - v[2] * 3)
|
||||
ops = place(name, target, properties) + ticks(20)
|
||||
if after:
|
||||
ops += place(after, target)
|
||||
ops += ticks(40) + restore(target)
|
||||
yield arrow(start, v, ops, crit=True)
|
||||
# Starting inside a block: stopped in place.
|
||||
for name in ['stone', 'oak_slab', 'oak_fence']:
|
||||
yield arrow((25.5, 9.25, 25.5), (.4, 0, .1), place(name, [(25, 9, 25)]) + ticks(10) + restore([(25, 9, 25)]))
|
||||
# Despawning 1200 ticks after sticking in the floor.
|
||||
for _ in range(2):
|
||||
yield arrow((rng.uniform(18, 30), 6, rng.uniform(4, 30)), (0, -1, 0), ticks(1215))
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / 'rust-arrow-parity'
|
||||
build.mkdir(exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
|
||||
resource_hash = client.resource_fingerprint(resources)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaArrowOracle.java'
|
||||
helpers = [oracle.with_name(name + '.java') for name in ['VanillaSceneCollisionOracle', 'VanillaRegistryCollisionScanOracle',
|
||||
'VanillaHeightmapOracle', 'VanillaCollisionOracle', 'VanillaBlockStateCodecOracle', 'VanillaSuffocationOracle',
|
||||
'VanillaFaceSupportOracle', 'VanillaEntityAttributeOracle', 'VanillaBlockLandingOracle', 'VanillaMovementRegistryOracle', 'VanillaDamageSourceOracle']]
|
||||
sources = [Path(__file__), lab.ROOT / 'tools/test_native_client.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py',
|
||||
oracle, *helpers, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/arrow_probe.rs']
|
||||
for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']:
|
||||
sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))]
|
||||
tested = base.source_hashes(sources)
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, libraries))
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars.get('server', jars['client'])) + os.pathsep + dependencies,
|
||||
'-d', classes, oracle, *helpers], 'compile-java')
|
||||
fixtures = list(corpus())
|
||||
operations = sum(len(f['ops']) for f in fixtures)
|
||||
expected = 2 * operations + len(fixtures)
|
||||
(build / 'inputs.txt').write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures))
|
||||
input_hash = lab.digest(build / 'inputs.txt', 'sha256')
|
||||
run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', 'arrow_probe'], 'compile-rust')
|
||||
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
|
||||
binary = Path(metadata['target_directory']) / 'debug/examples' / ('arrow_probe.exe' if os.name == 'nt' else 'arrow_probe')
|
||||
run([binary, resources, build, '--describe'], 'describe')
|
||||
references = []
|
||||
for side, jar in jars.items():
|
||||
run(['java', '-Xmx768M', '-cp', os.pathsep.join([str(classes), str(jar), dependencies]),
|
||||
'dev.horizonlab.parity.VanillaArrowOracle', side, build, resources], side)
|
||||
run([binary, resources, build, side], 'rust-' + side)
|
||||
matched = base.compare(build / (side + '.txt'), build / ('rust-' + side + '.txt'))
|
||||
if matched != expected:
|
||||
raise AssertionError('Incomplete arrow output')
|
||||
references.append({'side': side, 'jar_sha256': lab.digest(jar, 'sha256'), 'output_sha256': lab.digest(build / (side + '.txt'), 'sha256'),
|
||||
'matched_output_lines': matched, 'rust_output_sha256': lab.digest(build / ('rust-' + side + '.txt'), 'sha256')})
|
||||
print(f'{side}: {matched:,} arrow states match', flush=True)
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
if resource_hash != client.resource_fingerprint(resources) or input_hash != lab.digest(build / 'inputs.txt', 'sha256'):
|
||||
raise AssertionError('Arrow inputs changed during verification')
|
||||
lab.write_json(report, {'schema': 1, 'minecraft': lock['minecraft']['version'], 'manifest_sha1': lock['minecraft']['manifest_sha1'],
|
||||
'platform': platform.platform(), 'rustc': subprocess.check_output(['rustc', '--version'], text=True).strip(),
|
||||
'java': subprocess.check_output(['java', '--version'], text=True).splitlines()[0], 'fixtures': len(fixtures),
|
||||
'operations': operations, 'sources_sha256': tested, 'resources': resource_hash, 'input_sha256': input_hash,
|
||||
'references': references, 'scope': __doc__})
|
||||
print(f'Arrow parity passed: {report}', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user