diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 3f7562e0b..7be650c32 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3840,7 +3840,12 @@ impl Game<'_> { } self.crack_particle(crack.0, crack.1, state); let m = self.mining.as_mut().ok_or("mining")?; - if m.progress >= 1.0 { + // ServerPlayerGameMode breaks a player's block at once only when it is instant (START's + // insta-mine); otherwise it waits for the client's STOP_DESTROY_BLOCK + // (`guest_stop_digging`), never breaking it on its own count. Breaking it here would + // take the block from under the player's crack before the player's client predicts the + // break, so it gets neither particles nor sound. + if m.progress >= 1.0 && (self.lan_acting.is_none() || m.ticks == 1) { let pos = m.pos; self.mining = None; self.break_block(pos)?; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 76f622d9c..a61ea2a11 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -2277,7 +2277,7 @@ mod sensor_scan_tests { use horizon_core::geometry::Vec3; use serde_json::json; - fn kind() -> Arc { + pub(super) fn kind() -> Arc { Arc::new(MobType { id: "minecraft:cow".into(), species: Species::Cow, @@ -2481,56 +2481,9 @@ mod sensor_scan_tests { } #[cfg(test)] mod push_tests { + use super::sensor_scan_tests::kind; use super::*; use horizon_core::geometry::Vec3; - use serde_json::json; - - fn kind() -> Arc { - Arc::new(MobType { - id: "minecraft:cow".into(), - species: Species::Cow, - width: 0.9, - height: 1.4, - eye_height: 1.3, - category: "creature".into(), - max_health: 10.0, - speed: 0.2, - flying_speed: 0.4, - attack_damage: 0.0, - attack_knockback: 0.0, - follow_range: 16.0, - step_height: 0.6, - armor: 0.0, - armor_toughness: 0.0, - knockback_resistance: 0.0, - jump_strength: 0.42, - attributes: Arc::default(), - gravity: 0.08, - safe_fall_distance: 3.0, - fall_damage_multiplier: 1.0, - water_efficiency: 0.0, - water_slowdown: 0.8, - air_speed: 0.02, - baby_scale: 0.5, - head_rot_speed: 10.0, - max_head_x_rot: 40.0, - max_head_y_rot: 75.0, - ambient_interval: 120, - flags: Flags { - animal: true, - ..Default::default() - }, - model: Arc::new(Part::parse("root", &json!({}))), - layers: HashMap::new(), - texture: String::new(), - brain: Brain::Passive, - anim: Anim::Rabbit, - sounds: [""; 3], - step_sound: None, - food: Arc::default(), - tempt: Arc::default(), - }) - } /// The pending pushes as one list, scanned for each mob, as before. fn take_old(events: &mut Vec, from: usize, pending: &mut Vec<(u32, Vec3)>) { diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 331870b4a..bd0eb9c90 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -9,7 +9,12 @@ //! own random drives positions, sounds and jumps. `RunOne` shuffles with a //! random of its own, seeded with the brain's `shuffle_seed` when it is //! built. -use super::{Mob, MobEvent, MobWorld, Species, Who, path::Path, sniffer}; +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, + path::Path, + sniffer, +}; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource}, @@ -603,22 +608,7 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -794,37 +784,6 @@ fn followable_friendly(s: Species) -> bool { // ---- Behaviours ------------------------------------------------------------ -/// `Behavior`'s running state and end time. -#[derive(Clone, Copy, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let bound = self.max.wrapping_add(1).wrapping_sub(self.min); - let d = self - .min - .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); - self.end = cx.now + i64::from(d); - } - fn timed_out(&self, now: i64) -> bool { - now > self.end - } -} - /// `RunOne`: shuffles its children by weight and starts the first that can. #[derive(Clone, Debug)] struct Gate { @@ -1076,7 +1035,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).walk_target.clear(); mem(m).look_target.clear(); m.add_effect("minecraft:regeneration", 200, 0); @@ -1086,7 +1045,7 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::AnimalPanic { t, .. } => { @@ -1094,7 +1053,7 @@ impl B { if !(mm.hurt_by.get() == Some(&true) || mm.is_panicking.present()) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1123,7 +1082,7 @@ impl B { let reached = reached(m, cx.w, &walk); if !reached && compute_path(m, cx, &walk, path, speed) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); return true; @@ -1139,21 +1098,21 @@ impl B { if !mem(m).temptation_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::CountDownGaze(t) => { if !mem(m).gaze_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::CountDownTransport(t) => { if !mem(m).transport_items_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::Transport(x) => x.try_start(m, cx), @@ -1171,7 +1130,7 @@ impl B { let Some(partner) = breed_partner(m, cx.w) else { return false; }; - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1200,7 +1159,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1210,14 +1169,14 @@ impl B { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::FeelingHappy(t) => { if !mem(m).sniffer_happy.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::FEELING_HAPPY); true } @@ -1233,7 +1192,7 @@ impl B { if !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::DIGGING); true } @@ -1246,7 +1205,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::RISING); true } @@ -1261,7 +1220,7 @@ impl B { if !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SEARCHING); true } @@ -1278,7 +1237,7 @@ impl B { if is_tempted(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SCENTING); true } @@ -1293,12 +1252,12 @@ impl B { if m.is_baby() || !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SNIFFING); true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::AxolotlAction { .. } diff --git a/crates/horizon-client/src/mobs/brain.rs b/crates/horizon-client/src/mobs/brain.rs index da83ee93d..67bb6a2a6 100644 --- a/crates/horizon-client/src/mobs/brain.rs +++ b/crates/horizon-client/src/mobs/brain.rs @@ -1,8 +1,11 @@ //! Pieces of vanilla's `Brain` that species implemented as brains share: //! memories that expire, behaviour durations, walk targets and //! `MoveToTargetSink`. -use super::{Mob, goals::Cx}; -use horizon_core::random::RandomSource; +use super::{Mob, MobWorld, Who, goals::Cx}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; /// A memory with an expiry (`Brain.setMemoryWithExpiry`): present for the /// tick it was set and `ttl` more ticks. `Ttl::default()` is absent. @@ -25,6 +28,57 @@ impl Ttl { } } } +/// `Behavior`'s bookkeeping in the brains ported behaviour for behaviour +/// (villager, animal, monster, warden): running, and until when. +#[derive(Clone, Copy, Debug)] +pub struct Timed { + pub running: bool, + pub end: i64, + pub min: i32, + pub max: i32, +} +impl Timed { + pub fn new(min: i32, max: i32) -> Self { + Self { + running: false, + end: 0, + min, + max, + } + } + /// `Behavior.tryStart`'s duration draw from the level random, in Java's + /// int arithmetic (made even when it cannot vary). + pub fn begin(&mut self, lr: &mut LegacyRandom, now: i64) { + self.running = true; + let bound = self.max.wrapping_add(1).wrapping_sub(self.min); + let d = self.min.wrapping_add(lr.next_int_bound(bound).unwrap_or(0)); + self.end = now + i64::from(d); + } + /// `Behavior.timedOut`. + pub fn timed_out(&self, now: i64) -> bool { + now > self.end + } +} +/// `NearestLivingEntitySensor`'s scan: the living entities (the player +/// among them) whose boxes meet the follow range around `m`, nearest first. +pub fn living_near(m: &Mob, w: &MobWorld) -> Vec { + let r = m.attrs.follow_range; + let area = m.bounds().inflate(Vec3::new(r, r, r)); + let mut found: Vec<(Who, f64)> = Vec::new(); + for o in w.others_near(area) { + if o.id != m.id && o.alive && o.bounds.intersects(area) { + found.push((Who::Mob(o.id), m.distance_sqr(o.position))); + } + } + if let Some(p) = &w.player + && p.alive + && p.bounds.intersects(area) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + found.into_iter().map(|(w, _)| w).collect() +} /// A random duration in `min..=max` (`Behavior`'s end time). pub fn duration(m: &mut Mob, min: i32, max: i32) -> i32 { if max <= min { diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 1099e0bc3..bc1d6ed10 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -11,9 +11,10 @@ //! seeded when the brain is built. use super::{ Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, goals::Cx, path::Path, - villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget}, + villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget, compute_path, reached}, }; use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{ @@ -129,6 +130,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} fn mem_ref(m: &Mob) -> &Memories { &brain(m).expect("brain").mem } @@ -292,22 +297,7 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -456,31 +446,6 @@ fn sense_breeze_attack(m: &mut Mob, w: &MobWorld) { // ---- Behaviours --------------------------------------------------------- -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw from the level random. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); - self.end = cx.now + i64::from(d); - } -} - /// `StartAttacking`'s target finders. #[derive(Clone, Copy, Debug)] enum Finder { @@ -607,14 +572,14 @@ impl B { if *creaking && !super::creaking::can_move(m) || !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LookAtTargetSink(t) => { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::MoveToTargetSink { @@ -636,9 +601,9 @@ impl B { } let walk = mm.walk_target.value().unwrap(); let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -719,7 +684,7 @@ impl B { true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::RandomStroll(running, speed) => { @@ -848,7 +813,7 @@ impl B { mem(m).breeze_shoot.clear(); return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start super::breeze::set_pose(m, super::breeze::SHOOTING); mem(m).breeze_shoot_charging.set_ttl((), 15); @@ -867,7 +832,7 @@ impl B { if !long_jump_can_run(m, cx) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start if !mem(m).breeze_jump_inhaling.present() { mem(m).breeze_jump_inhaling.set_ttl((), 10); @@ -905,7 +870,7 @@ impl B { if !stuck { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).breeze_shoot.set_ttl((), 60); true } @@ -924,7 +889,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); slide_start(m, cx); true } @@ -989,7 +954,7 @@ impl B { && let Some(now_target) = walk.target.block(cx.w) { let d = manhattan_sq(now_target, last); - if d > 4 && compute_path(m, cx, &walk, path, speed) { + if d > 4 && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -1122,53 +1087,6 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { _ => true, } } -/// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { - walk.target.block(w).is_some_and(|p| { - let h = block_of(m.position); - (p[0] - h[0]).abs() + (p[1] - h[1]).abs() + (p[2] - h[2]).abs() <= walk.close - }) -} -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( - m: &mut Mob, - cx: &mut Bx, - walk: &WalkTarget, - path: &mut Option, - speed: &mut f32, -) -> bool { - let Some(target) = walk.target.block(cx.w) else { - return false; - }; - *path = m.create_path_to(cx.w, target, 0); - *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); - } else { - let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); - if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); - } - if path.is_some() { - return true; - } - let to = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) - { - *path = m.create_path_to(cx.w, block_of(Vec3::new(step[0], step[1], step[2])), 0); - return path.is_some(); - } - } - false -} /// `BehaviorUtils.isWithinAttackRange(body, target, 1)` for a mob without a /// ranged weapon: `Mob.isWithinMeleeAttackRange`. fn within_attack_range(m: &Mob, w: &MobWorld, target: Who) -> bool { diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 194bd75ff..df19d8fed 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -11,6 +11,7 @@ //! `Brain::shuffle_seed` when the brain is built. use super::{ Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, path::{Path, PathNode}, }; use horizon_core::{ @@ -341,6 +342,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -565,22 +570,7 @@ const FOLLOW_RANGE: f64 = 16.0; /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -791,34 +781,6 @@ fn sense_golem(m: &mut Mob, w: &MobWorld) { // ---- Behaviours --------------------------------------------------------- -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let bound = self.max.wrapping_add(1).wrapping_sub(self.min); - let d = self - .min - .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); - self.end = cx.now + i64::from(d); - } -} - /// The POI types villagers use. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Poi { @@ -1498,18 +1460,18 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LookAtTargetSink(t) => { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::PanicTrigger(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); // VillagerPanicTrigger.start if panic_condition(m) { if !brain_mut(m).is_active(Act::Panic) { @@ -1542,9 +1504,9 @@ impl B { } let walk = mm.walk_target.value().unwrap(); let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -1561,7 +1523,7 @@ impl B { if !follow_trading_condition(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); follow_trading_player(m); true } @@ -1573,7 +1535,7 @@ impl B { if !matches!(a, Act::Idle | Act::Work | Act::Play) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::JumpOnBed { @@ -1590,7 +1552,7 @@ impl B { if mm.walk_target.present() || !m.is_baby() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); *bed = Some(nearest); *time_left = 100; *jumps = 3 + cx.lr.next_int_bound(4).unwrap_or(0); @@ -1599,7 +1561,7 @@ impl B { true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::GiveGiftToHero { @@ -1618,7 +1580,7 @@ impl B { *until_next -= 1; return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); *given = false; *started = now; let mm = mem(m); @@ -1630,7 +1592,7 @@ impl B { if !mem(m).interaction_target.present() || !show_trades_condition(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start if let Some(target) = mem(m).interaction_target.value() { mem(m).look_target.set(Tracker::Entity(target, true)); @@ -1646,7 +1608,7 @@ impl B { if !villager_target_valid(m, cx.w, Mem::InteractionTarget) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let target = mem(m).interaction_target.value().unwrap(); lock_gaze(m, target, cx); true @@ -1659,7 +1621,7 @@ impl B { if !breeding_possible(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let target = mem(m).breed_target.value().unwrap(); lock_gaze(m, target, cx); *birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); @@ -1680,7 +1642,7 @@ impl B { if !closer_to_center(site, m.position, 1.73) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start let mm = mem(m); mm.last_worked_at_poi.set(now); @@ -1709,7 +1671,7 @@ impl B { *valid = farmland_around(m, cx.w); *target = pick_farmland(valid, cx); let Some(p) = *target else { return false }; - t.begin(cx); + t.begin(cx.lr, cx.now); if now > *next_ok { let mm = mem(m); mm.look_target.set(Tracker::Block(p)); @@ -2288,7 +2250,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if now > *next_ok { if super::villager::start_sleeping(m, home, w) { mem(m).last_slept.set(now); @@ -2609,7 +2571,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LocateHidingPlace { @@ -2769,7 +2731,7 @@ impl B { && let Some(now_target) = walk.target.block(cx.w) { let d = manhattan_sq(now_target, last); - if d > 4 && compute_path(m, cx, &walk, path, speed) { + if d > 4 && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -3141,33 +3103,37 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { } } /// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { +pub(super) fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { walk.target .block(w) .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) } -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( +/// `MoveToTargetSink.tryComputePath`, for the brains on these memories +/// (villager, monster, warden): `cant_reach` is the brain's +/// `CANT_REACH_WALK_TARGET_SINCE`. +pub(super) fn compute_path( m: &mut Mob, - cx: &mut Bx, + w: &MobWorld, + now: i64, walk: &WalkTarget, path: &mut Option, speed: &mut f32, + cant_reach: fn(&mut Mob) -> &mut Slot, ) -> bool { - let Some(target) = walk.target.block(cx.w) else { + let Some(target) = walk.target.block(w) else { return false; }; - *path = m.create_path_to(cx.w, target, 0); + *path = m.create_path_to(w, target, 0); *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); + if reached(m, w, walk) { + cant_reach(m).clear(); } else { let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); + let since = cant_reach(m); if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); + since.clear(); + } else if !since.present() { + since.set(now); } if path.is_some() { return true; @@ -3178,14 +3144,14 @@ fn compute_path( f64::from(target[2]) + 0.5, ]; if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) + m.default_random_pos_towards(w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) { let p = [ step[0].floor() as i32, step[1].floor() as i32, step[2].floor() as i32, ]; - *path = m.create_path_to(cx.w, p, 0); + *path = m.create_path_to(w, p, 0); return path.is_some(); } } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 518347e77..8caafefc9 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -14,9 +14,10 @@ //! shuffle seed. use super::{ Mob, MobEvent, MobWorld, Who, + brain::Timed, goals::Cx, path::Path, - villager_brain::{Slot, Tracker, Visible, WalkTarget}, + villager_brain::{Slot, Tracker, Visible, WalkTarget, compute_path, reached}, warden::{self, Pose}, }; use horizon_core::{ @@ -145,31 +146,6 @@ impl Memories { } } -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw (made even when it cannot vary). - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); - self.end = cx.now + i64::from(d); - } -} - /// `RunOne`'s `ShufflingList` over a stroll (weight 2) and `DoNothing` (1). #[derive(Clone, Debug)] struct Gate { @@ -383,6 +359,10 @@ fn brain(m: &Mob) -> Option<&Brain> { pub(super) fn mem(m: &mut Mob) -> &mut Memories { &mut m.extra.warden.as_mut().expect("a warden").brain.mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -558,9 +538,6 @@ fn find_closest(m: &mut Mob, w: &MobWorld, filter: impl Fn(&Mob, Who) -> bool) - fn block_of(p: Vec3) -> [i32; 3] { [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] } -fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { - (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() -} fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { (0..3).map(|i| i64::from(a[i] - b[i]).pow(2)).sum() } @@ -607,57 +584,6 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { _ => true, } } -/// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { - walk.target - .block(w) - .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) -} -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( - m: &mut Mob, - cx: &mut Bx, - walk: &WalkTarget, - path: &mut Option, - speed: &mut f32, -) -> bool { - let Some(target) = walk.target.block(cx.w) else { - return false; - }; - *path = m.create_path_to(cx.w, target, 0); - *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); - } else { - let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); - if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); - } - if path.is_some() { - return true; - } - let to = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) - { - let p = [ - step[0].floor() as i32, - step[1].floor() as i32, - step[2].floor() as i32, - ]; - *path = m.create_path_to(cx.w, p, 0); - return path.is_some(); - } - } - false -} fn same_path(a: Option<&Path>, b: Option<&Path>) -> bool { match (a, b) { (None, None) => true, @@ -710,7 +636,7 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::SetWardenLookTarget(r) => one(r, || { @@ -732,7 +658,7 @@ impl B { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::MoveToTargetSink { @@ -755,9 +681,9 @@ impl B { return false; }; let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -775,7 +701,7 @@ impl B { if !mm.is_emerging.present() || mm.walk_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); warden::set_pose(m, Pose::Emerging); sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); true @@ -791,7 +717,7 @@ impl B { if !(m.on_ground || liquid) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if m.on_ground { warden::set_pose(m, Pose::Digging); sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); @@ -872,7 +798,7 @@ impl B { true }), B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::GoToDisturbance(r) => one(r, || { @@ -907,7 +833,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); true } @@ -919,7 +845,7 @@ impl B { let Some(target) = mm.roar_target.value() else { return false; }; - t.begin(cx); + t.begin(cx.lr, cx.now); let mm = mem(m); mm.roar_sound_delay.set_ttl((), ROAR_SOUND_DELAY); mm.walk_target.clear(); @@ -1004,7 +930,7 @@ impl B { if !close { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let mm = mem(m); mm.attack_cooling_down .set_ttl(true, i64::from(SONIC_DURATION)); @@ -1092,7 +1018,7 @@ impl B { && let Some(walk) = mem(m).walk_target.value() && let Some(now_target) = walk.target.block(cx.w) && dist_sqr(now_target, last) > 4 - && compute_path(m, cx, &walk, path, speed) + && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); diff --git a/crates/horizon-world/src/datafix/chunk_flatten.rs b/crates/horizon-world/src/datafix/chunk_flatten.rs index e3c116d93..671fc9f73 100644 --- a/crates/horizon-world/src/datafix/chunk_flatten.rs +++ b/crates/horizon-world/src/datafix/chunk_flatten.rs @@ -266,8 +266,8 @@ fn is_virtual(block: usize) -> bool { VIRTUAL.contains(&block) } -/// `getSideMask`. -fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { +/// `getSideMask` (LeavesFix has the same copy). +pub(super) fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { let mut s = 0; if north { if east { diff --git a/crates/horizon-world/src/datafix/chunk_leaves.rs b/crates/horizon-world/src/datafix/chunk_leaves.rs index 9cd2fd3d9..07d59cbdf 100644 --- a/crates/horizon-world/src/datafix/chunk_leaves.rs +++ b/crates/horizon-world/src/datafix/chunk_leaves.rs @@ -6,6 +6,7 @@ //! emulated here (`IntOpenHashSet` and the key order of an `Int2ObjectOpenHashMap`). use std::collections::{HashMap, HashSet}; +use super::chunk_flatten::side_mask; use super::dynamic::{as_int, as_long_stream, as_str, ceillog2, set}; use crate::nbt::Tag; @@ -355,32 +356,6 @@ fn get_index(x: i32, y: i32, z: i32) -> i32 { y << 8 | z << 4 | x } -fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { - let mut s = 0; - if north { - if east { - s |= 2; - } else if west { - s |= 128; - } else { - s |= 1; - } - } else if south { - if west { - s |= 32; - } else if east { - s |= 8; - } else { - s |= 16; - } - } else if east { - s |= 4; - } else if west { - s |= 64; - } - s -} - /// `LeavesFix` over a chunk (`{Level: ...}`). pub(super) fn leaves_fix(chunk: &mut Tag) { let Some(level) = chunk.get_mut("Level") else { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 7a36ba526..223f1fb85 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -4959,5 +4959,73 @@ CHECKS += ['fishing'] CHECK_FNS.update(fishing=check_fishing) +def check_digging(host, guest, out): + """The server breaks a block a player digs only once that player's client is done + (ServerPlayerGameMode: STOP_DESTROY_BLOCK, or the delayed destroy), never on its own count, so + the player's client always breaks it first, with its particles and sound. The guest holds + attack across a wall of six oak logs with a copper axe and hears each one break; then it digs + stone with a wooden pickaxe and its game stalls for a second halfway: the stone is still there + on both sides when it resumes, and the guest's own crack finishes it.""" + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + x, y, z = gx + 3, gy, gz + 4 + heard = lambda sound: guest('status')['heard'].get(sound, 0) + at = lambda b: (f'{b[0] + 0.02:.2f}', f'{b[1] + 0.5:.2f}', f'{b[2] + 0.5:.2f}') + guest('command', command='gamemode survival') + guest('command', command='item replace entity @s weapon.mainhand with minecraft:copper_axe') + host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 4} {y + 3} {z + 2} minecraft:air') + host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 4} {y - 1} {z + 2} minecraft:stone') + host('command', command=f'fill {x + 2} {y} {z - 1} {x + 2} {y + 1} {z + 1} minecraft:oak_log') + guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + guest.wait(30) + logs = [(x + 2, y + dy, z + dz) for dz in (-1, 0, 1) for dy in (0, 1)] + before = heard('minecraft:block.wood.break') + guest.raw('look-at', *at(logs[0])) + guest.raw('mouse', 'left', 'down') + left = list(logs) + deadline = time.time() + 20 + while left and time.time() < deadline: + if guest.raw('block', *left[0]).get('block') != 'minecraft:oak_log': + left.pop(0) + if left: + guest.raw('look-at', *at(left[0])) + guest.raw('mouse', 'left', 'up') + guest.wait(10) + seen = {'logs_left': left, 'log_breaks_heard': heard('minecraft:block.wood.break') - before} + + # Stone with a wooden pickaxe: 23 ticks. The guest stalls for a second after about 8. + stone = (x + 2, y, z) + guest('command', command='item replace entity @s weapon.mainhand with minecraft:wooden_pickaxe') + host('command', command=f'setblock {stone[0]} {stone[1]} {stone[2]} minecraft:stone') + guest.wait(10) + before = heard('minecraft:block.stone.break') + guest.raw('look-at', *at(stone)) + guest.raw('mouse', 'left', 'down') + time.sleep(0.4) + os.kill(guest.pid, signal.SIGSTOP) + try: + time.sleep(1.0) + finally: + os.kill(guest.pid, signal.SIGCONT) + resumed = {'guest': guest.raw('block', *stone).get('block'), 'server': host.raw('block', *stone).get('block'), + 'mining': guest('state').get('mining')} + # Let go once it breaks: past it the crosshair reaches the floor. + deadline = time.time() + 5 + while guest.raw('block', *stone).get('block') == 'minecraft:stone' and time.time() < deadline: + pass + guest.raw('mouse', 'left', 'up') + guest.wait(10) + seen.update(resumed=resumed, stone_after=host.raw('block', *stone).get('block'), + stone_breaks_heard=heard('minecraft:block.stone.break') - before) + guest.shot(out, 'digging') + assert not left and seen['log_breaks_heard'] == 6, f'the server broke logs before the guest did: {seen}' + assert resumed['guest'] == resumed['server'] == 'minecraft:stone', f'the server broke the stone while the guest stalled: {seen}' + assert seen['stone_after'] == 'minecraft:air' and seen['stone_breaks_heard'] == 1, f'the guest did not break the stone: {seen}' + return seen + + +CHECKS += ['digging'] +CHECK_FNS.update(digging=check_digging) + + if __name__ == '__main__': main()