diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 9d93e6175..059aaf58b 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -57,6 +57,8 @@ enum Animate { drag: bool, }, Fire, + /// An active sculk sensor. + SculkSensor, } fn step(facing: &str) -> [i32; 3] { match facing { @@ -128,6 +130,11 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { drag: prop("drag").as_deref() == Some("true"), }, "fire" | "soul_fire" => Animate::Fire, + "sculk_sensor" | "calibrated_sculk_sensor" + if prop("sculk_sensor_phase").as_deref() == Some("active") => + { + Animate::SculkSensor + } _ if name.ends_with("candle_cake") && lit => Animate::CandleCake, _ if (name == "candle" || name.ends_with("_candle")) && lit => { Animate::Candles(prop("candles").and_then(|c| c.parse().ok()).unwrap_or(1)) @@ -905,6 +912,35 @@ fn block_animate_tick( } } } + Animate::SculkSensor => { + // SculkSensorBlock.animateTick. + let r = engine.random(); + let direction = r.next_int_bound(6).unwrap_or(0); + // Direction.values(): down, up, north, south, west, east. + if direction >= 2 { + let step = [[0, 0, -1], [0, 0, 1], [-1, 0, 0], [1, 0, 0]][direction as usize - 2]; + let x = fx + + 0.5 + + if step[0] == 0 { + 0.5 - r.next_double() + } else { + f64::from(step[0]) * 0.6 + }; + let z = fz + + 0.5 + + if step[2] == 0 { + 0.5 - r.next_double() + } else { + f64::from(step[2]) * 0.6 + }; + let ya = f64::from(r.next_float() * 0.04); + engine.add( + &crate::particles::ParticleOptions::sculk_to_redstone(), + [x, fy + 0.25, z], + [0.0, ya, 0.0], + ); + } + } Animate::RespawnAnchor => { let r = engine.random(); if next_int(r, 100) == 0 { diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6d999c9a8..101a439b0 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -58,6 +58,8 @@ pub enum BlockEntity { Beacon(Box), /// `LecternBlockEntity`: the book and the open page. Lectern(Lectern), + /// Sculk sensors, shriekers and catalysts (`crate::sculk`). + Sculk(Box), } #[derive(Clone, Debug, Default)] pub struct Lectern { @@ -104,6 +106,9 @@ impl BlockEntity { if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } + if let Some(sculk) = crate::sculk::SculkEntity::for_block(name) { + return Some(Self::Sculk(Box::new(sculk))); + } if name == "minecraft:beacon" { return Some(Self::Beacon(Box::new(Beacon { last_check_y: i32::MIN / 2, @@ -155,6 +160,7 @@ impl BlockEntity { Self::Jukebox(_) => "minecraft:jukebox", Self::Beacon(_) => "minecraft:beacon", Self::Lectern(_) => "minecraft:lectern", + Self::Sculk(s) => s.id(), } } pub fn contents(&self) -> Vec { @@ -166,6 +172,7 @@ impl BlockEntity { Self::Jukebox(j) => j.record.iter().cloned().collect(), Self::Beacon(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), + Self::Sculk(_) => Vec::new(), } } pub fn slots(&self) -> &[Option] { @@ -173,7 +180,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &f.items, Self::Brewing(b) => &b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::Sculk(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -181,7 +192,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, Self::Brewing(b) => &mut b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::Sculk(_) => &mut [], } } } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index a655c2dcd..b0f12b18f 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -314,6 +314,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { "minecraft:wither" => { map.insert("Invul".into(), Tag::Int(m.extra.counter)); } + "minecraft:warden" => { + if let Some(st) = &m.extra.warden { + map.insert("listener".into(), st.vibration.to_nbt()); + map.insert( + "anger".into(), + Tag::compound([("suspects", Tag::List(Vec::new()))]), + ); + } + } "minecraft:ravager" => { map.insert("AttackTick".into(), Tag::Int(m.extra.counter)); map.insert("StunTick".into(), Tag::Int(m.extra.counter2)); @@ -565,6 +574,13 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - if m.species() == crate::mobs::Species::Wither { m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32; } + if m.species() == crate::mobs::Species::Warden { + // The brain starts afresh: a minute before it digs back down. + crate::mobs::warden::finalize(&mut m, false, &mut Vec::new()); + if let (Some(st), Some(listener)) = (m.extra.warden.as_mut(), tag.get("listener")) { + st.vibration = crate::sculk::Data::from_nbt(listener); + } + } if m.species() == crate::mobs::Species::Ravager { m.extra.counter = number(tag.get("AttackTick")).unwrap_or(0) as i32; m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 66925932c..d46e6ab74 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -46,6 +46,7 @@ mod remote; mod render_control; mod render_tick; mod screens; +mod sculk; mod shield; mod sign_edit; mod station_control; @@ -299,9 +300,12 @@ impl LevelAccess for GameLevel<'_> { fn block_entity_analog_signal( &self, pos: BlockPos, - _state: BlockStateId, + state: BlockStateId, _direction: Direction, ) -> i32 { + if let Some(signal) = sculk::sensor_signal(self.world, self.behaviours, state, pos) { + return signal; + } if let Some((_, comparator)) = jukebox::jukebox_signals(self.world, self.items, pos) { return comparator; } @@ -517,6 +521,7 @@ struct Game<'a> { mobs: Vec, arrows: Vec, creatures: creatures::Creatures, + sculk: sculk::SculkState, attack_ticks: u32, last_hurt_by_player: HashSet, chest_open: HashMap<(i32, i32, i32), (f32, f32)>, @@ -1226,6 +1231,12 @@ impl Game<'_> { sounds.pitch * 0.8, ); } + LevelEvent::LevelEvent { + id: 3006, + pos, + data, + } => self.sculk_charge_event(pos, data), + LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), LevelEvent::LevelEvent { id, pos, .. } => { let c = Some([ f64::from(pos.x) + 0.5, @@ -1375,10 +1386,17 @@ impl Game<'_> { }, ); } + LevelEvent::GameEvent { pos, event, state } => { + self.sculk_level_event(pos, event, state) + } + LevelEvent::BlockEvent { + pos, + state, + kind: "shrieker_respond", + } => self.shrieker_block_event(pos, state), LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } - | LevelEvent::BlockEvent { .. } - | LevelEvent::GameEvent { .. } => {} + | LevelEvent::BlockEvent { .. } => {} } } Ok(()) @@ -1536,6 +1554,9 @@ impl Game<'_> { self.process_level_events() } fn break_block(&mut self, pos: [i32; 3]) -> Result<()> { + self.with_player_actor(|game| game.break_block_as_player(pos)) + } + fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> { let state = self.world.block(pos[0], pos[1], pos[2]); let facts = self.res.facts.get(state).clone(); // Block.playerWillDestroy: mining their gold angers all nearby piglins. @@ -1632,6 +1653,9 @@ impl Game<'_> { Ok(()) } fn use_item(&mut self) -> Result<()> { + self.with_player_actor(|game| game.use_item_as_player()) + } + fn use_item_as_player(&mut self) -> Result<()> { // Spectators only look (MultiPlayerGameMode.useItemOn/useItem pass). if self.spectator() { return Ok(()); @@ -2470,6 +2494,7 @@ impl Game<'_> { self.bob.1 += (target - self.bob.1) * 0.4; } self.tick_block_entities()?; + self.tick_sculk()?; self.tick_brewing_stands()?; if let Some(r) = &self.renderer { let eye = self.player.as_ref().map(|p| { @@ -3040,7 +3065,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::Sculk(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3265,7 +3291,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::Sculk(_), ) => {} None => { let texture = if self.craft_size == 3 { @@ -7597,6 +7624,7 @@ pub fn run() -> Result<()> { mobs: Vec::new(), arrows: Vec::new(), creatures: Default::default(), + sculk: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), chest_open: HashMap::new(), diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f2cbf245e..31abb2adf 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -639,6 +639,17 @@ impl Game<'_> { /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + // LivingEntity.die: the death is heard, and a sculk catalyst nearby + // takes the experience. + self.sculk_mob_died(m); + let consumed = + self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |game| { + if by_player { + experience_reward(m, &mut game.world.random) + } else { + 0 + } + }); if by_player { self.stats.add("killed", &m.kind.id, 1); self.stats.custom("mob_kills", 1); @@ -720,7 +731,7 @@ impl Game<'_> { } } } - if by_player { + if by_player && !consumed { let xp = experience_reward(m, &mut self.world.random); if xp > 0 { self.spawn_orbs(pos, xp); @@ -970,6 +981,11 @@ impl Game<'_> { } }, MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::Vibration { from, to, ticks } => { + self.mob_vibration_particle(from, to, ticks) + } + MobEvent::DigParticles { at } => self.warden_dig_particles(at), + MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius), MobEvent::GiftLoot { table, at } => { let drops = self.res diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs new file mode 100644 index 000000000..ac6b79221 --- /dev/null +++ b/crates/horizon-client/src/game/sculk.rs @@ -0,0 +1,1369 @@ +//! Game events and sculk on the game side: dispatching events to sculk +//! sensors, shriekers and wardens (`GameEventDispatcher`), the vibration +//! ticker, redstone output, resonance, shrieks and warden summoning +//! (`SculkShriekerBlockEntity`, `SpawnUtil`), catalysts feeding the sculk +//! spreader from deaths, and the darkness wardens and shriekers cast. +use super::{Game, Result}; +use horizon_client::{ + containers::BlockEntity, + mobs::{Mob, Species, Who, warden}, + particles::{ParticleOptions, ParticleType}, + sculk::{self, Context, Info, SculkEntity, SculkKind, WardenSpawnTracker}, +}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; +use horizon_world::registry::BlockStateId; +use std::collections::{HashMap, HashSet}; +use winit::keyboard::KeyCode; + +/// The sculk block kinds by state id, built once. +#[derive(Default)] +struct Tables { + built: bool, + /// 0 none, 1 sensor, 2 calibrated sensor, 3 shrieker, 4 catalyst. + kinds: Vec, + occludes: Vec, + dampens: Vec, + resonator: Vec, +} +/// `SculkSensorBlock.getAnalogOutputSignal`: the last vibration's frequency +/// while the sensor is active. +pub(super) fn sensor_signal( + world: &horizon_client::world::World, + behaviours: &horizon_world::level::Behaviours, + state: BlockStateId, + pos: BlockPos, +) -> Option { + match world.block_entities.get(&(pos.x, pos.y, pos.z)) { + Some(BlockEntity::Sculk(e)) + if matches!(e.kind, SculkKind::Sensor | SculkKind::Calibrated) => + { + Some(if behaviours.sculk_sensor_active(state) { + e.last_frequency + } else { + 0 + }) + } + _ => None, + } +} +/// `Entity.moveDist` / `nextStep` and the last state, per entity. +#[derive(Clone, Copy, Debug)] +struct Steps { + move_dist: f32, + next_step: f32, + last: [f64; 3], + on_ground: bool, + in_water: bool, +} +#[derive(Default)] +pub(super) struct SculkState { + /// The player's warning level toward a warden. + pub tracker: WardenSpawnTracker, + tables: Tables, + index: HashSet<(i32, i32, i32)>, + known: HashSet<(i32, i32)>, + steps: HashMap, + damaged: HashMap, + last_health: Option, + /// Who causes the block changes being processed (the player's actions). + pub actor: Option, + ticks: u32, +} +const KIND_SENSOR: u8 = 1; +const KIND_CALIBRATED: u8 = 2; +const KIND_SHRIEKER: u8 = 3; +const KIND_CATALYST: u8 = 4; + +fn center(p: (i32, i32, i32)) -> [f64; 3] { + [ + f64::from(p.0) + 0.5, + f64::from(p.1) + 0.5, + f64::from(p.2) + 0.5, + ] +} +fn block_of(p: [f64; 3]) -> [i32; 3] { + [ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ] +} +fn dist_sqr(a: [i32; 3], b: (i32, i32, i32)) -> i64 { + let d = |x: i32, y: i32| i64::from(x) - i64::from(y); + d(a[0], b.0).pow(2) + d(a[1], b.1).pow(2) + d(a[2], b.2).pow(2) +} + +impl Game<'_> { + /// Run `f` with the player as the cause of the block changes it makes. + pub(super) fn with_player_actor(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { + let prior = self.sculk.actor.replace(Who::Player); + let out = f(self); + self.sculk.actor = prior; + out + } + + // ---- setup and the block entity index ---- + + fn sculk_prepare(&mut self) { + if self.sculk.tables.built { + return; + } + let registry = self.res.assets.registry; + let n = registry.len(); + let tag = |name: &str| { + self.res + .items + .block_tags + .get(name) + .cloned() + .unwrap_or_default() + }; + let (wool, dampening, resonators) = ( + tag("minecraft:occludes_vibration_signals"), + tag("minecraft:dampens_vibrations"), + tag("minecraft:vibration_resonators"), + ); + let mut t = Tables { + built: true, + kinds: vec![0; n], + occludes: vec![false; n], + dampens: vec![false; n], + resonator: vec![false; n], + }; + for i in 0..n { + let facts = self.res.facts.get(BlockStateId(i as u32)); + let name: &str = &facts.name; + t.kinds[i] = match name { + "minecraft:sculk_sensor" => KIND_SENSOR, + "minecraft:calibrated_sculk_sensor" => KIND_CALIBRATED, + "minecraft:sculk_shrieker" => KIND_SHRIEKER, + "minecraft:sculk_catalyst" => KIND_CATALYST, + _ => 0, + }; + t.occludes[i] = wool.contains(name); + t.dampens[i] = dampening.contains(name); + t.resonator[i] = resonators.contains(name); + } + self.world.watched = t.kinds.iter().map(|k| *k != 0).collect(); + self.sculk.tables = t; + } + fn kind_of_state(&self, state: u16) -> u8 { + self.sculk + .tables + .kinds + .get(usize::from(state)) + .copied() + .unwrap_or(0) + } + fn state_is(&self, table: &[bool], state: BlockStateId) -> bool { + table.get(state.0 as usize).copied().unwrap_or(false) + } + fn entity_for_kind(kind: u8) -> Option { + Some(SculkEntity::new(match kind { + KIND_SENSOR => SculkKind::Sensor, + KIND_CALIBRATED => SculkKind::Calibrated, + KIND_SHRIEKER => SculkKind::Shrieker, + KIND_CATALYST => SculkKind::Catalyst, + _ => return None, + })) + } + /// Find the sculk blocks of chunks that just became resident, and apply + /// the block writes recorded since the last tick. + fn sculk_sync_index(&mut self) { + // Chunks that arrived or left (every half second is plenty). + if self.sculk.ticks.is_multiple_of(10) { + let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); + for key in loaded.difference(&self.sculk.known.clone()) { + self.sculk_scan_chunk(*key); + } + let gone: Vec<(i32, i32)> = self.sculk.known.difference(&loaded).copied().collect(); + for key in gone { + self.sculk.index.retain(|p| (p.0 >> 4, p.2 >> 4) != key); + } + self.sculk.known = loaded; + } + let writes = std::mem::take(&mut self.world.watched_writes); + for (key, old, new) in writes { + let (old_kind, new_kind) = (self.kind_of_state(old), self.kind_of_state(new)); + if old_kind == new_kind { + continue; + } + // SculkShriekerBlockEntity.preRemoveSideEffects. + if old_kind == KIND_SHRIEKER + && let Some(BlockEntity::Sculk(e)) = self.world.block_entities.get(&key) + && self.shrieker_shrieking(BlockStateId(u32::from(old))) + { + let warning = e.warning_level; + self.shrieker_respond(key, BlockStateId(u32::from(old)), warning); + } + if matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Sculk(_)) + ) { + self.world.block_entities.remove(&key); + } + self.sculk.index.remove(&key); + if let Some(e) = Self::entity_for_kind(new_kind) { + self.world + .block_entities + .insert(key, BlockEntity::Sculk(Box::new(e))); + self.sculk.index.insert(key); + } + } + } + fn sculk_scan_chunk(&mut self, key: (i32, i32)) { + use horizon_client::chunk::{Blocks, MIN_Y}; + let Some(chunk) = self.world.chunks.get(&key).cloned() else { + return; + }; + let mut found = Vec::new(); + for (s, section) in chunk.sections.iter().enumerate() { + let y0 = MIN_Y + s as i32 * 16; + match §ion.blocks { + Blocks::Uniform(v) => { + // A uniform section of sculk blocks does not exist. + let _ = v; + } + Blocks::Full(a) => { + for (i, v) in a.iter().enumerate() { + if self.kind_of_state(*v) != 0 { + let (x, z, y) = (i & 15, (i >> 4) & 15, i >> 8); + found.push(( + key.0 * 16 + x as i32, + y0 + y as i32, + key.1 * 16 + z as i32, + *v, + )); + } + } + } + } + } + for (x, y, z, state) in found { + let pos = (x, y, z); + if !matches!( + self.world.block_entities.get(&pos), + Some(BlockEntity::Sculk(_)) + ) && let Some(e) = Self::entity_for_kind(self.kind_of_state(state)) + { + self.world + .block_entities + .insert(pos, BlockEntity::Sculk(Box::new(e))); + } + self.sculk.index.insert(pos); + } + } + fn sculk_entity(&mut self, key: (i32, i32, i32)) -> Option<&mut SculkEntity> { + match self.world.block_entities.get_mut(&key) { + Some(BlockEntity::Sculk(e)) => Some(e), + _ => None, + } + } + + // ---- contexts ---- + + fn state_dampens(&self, state: Option) -> bool { + state.is_some_and(|s| self.state_is(&self.sculk.tables.dampens, s)) + } + /// `GameEvent.Context.of(player, state)`. + pub(super) fn player_context(&self, state: Option) -> Context { + let (dead, creative) = self + .player + .as_ref() + .map_or((true, true), |p| (p.health.dead_or_dying(), self.creative)); + Context { + source: Some(Who::Player), + owner: None, + dampening_state: self.state_dampens(state), + spectator: self.spectator(), + stepping_carefully: self.keys.contains(&KeyCode::ShiftLeft), + dampens: false, + targetable: !dead && !creative && !self.spectator(), + living: true, + player: true, + } + } + /// `GameEvent.Context.of(mob, state)`. + pub(super) fn mob_context(&self, id: u32, state: Option) -> Context { + let mob = self.mobs.iter().find(|m| m.id == id); + Context { + source: Some(Who::Mob(id)), + owner: None, + dampening_state: self.state_dampens(state), + spectator: false, + stepping_carefully: false, + dampens: mob.is_some_and(|m| m.species() == Species::Warden), + targetable: mob.is_some_and(|m| m.alive() && m.species() != Species::Warden), + living: true, + player: mob.is_some_and(|m| m.rider.is_some()), + } + } + pub(super) fn who_context(&self, who: Option, state: Option) -> Context { + match who { + Some(Who::Player) => self.player_context(state), + Some(Who::Mob(id)) => self.mob_context(id, state), + None => Context { + dampening_state: self.state_dampens(state), + ..Context::default() + }, + } + } + + // ---- posting ---- + + /// `Level.gameEvent`: tell the listeners within reach. + pub(super) fn post_game_event(&mut self, event: &'static str, pos: [f64; 3], ctx: Context) { + if self.remote.is_some() || !self.sculk.tables.built { + return; + } + let at = block_of(pos); + let radius = sculk::notification_radius(event).min(16); + let near: Vec<(i32, i32, i32)> = self + .sculk + .index + .iter() + .copied() + .filter(|p| dist_sqr(at, *p) <= i64::from(radius * radius)) + .collect(); + for key in near { + self.sculk_listen(key, event, pos, &ctx); + } + for i in 0..self.mobs.len() { + if self.mobs[i].species() == Species::Warden && self.mobs[i].alive() { + self.warden_listen(i, event, pos, &ctx); + } + } + } + /// A game event at a block (`Level.gameEvent(source, event, pos)`). + pub(super) fn post_block_game_event( + &mut self, + event: &'static str, + pos: [i32; 3], + who: Option, + state: Option, + ) { + let ctx = self.who_context(who, state); + self.post_game_event(event, center((pos[0], pos[1], pos[2])), ctx); + } + /// A game event of an entity at its position. + pub(super) fn post_entity_event(&mut self, event: &'static str, who: Who) { + let at = match who { + Who::Player => self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]), + Who::Mob(id) => self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| [m.position.x, m.position.y, m.position.z]), + }; + if let Some(at) = at { + let ctx = self.who_context(Some(who), None); + self.post_game_event(event, at, ctx); + } + } + /// `LevelEvent::GameEvent` from the block behaviour library. + pub(super) fn sculk_level_event( + &mut self, + pos: BlockPos, + event: &'static str, + state: Option, + ) { + let who = self.sculk.actor; + self.post_block_game_event(event, [pos.x, pos.y, pos.z], who, state); + } + + fn occluded(&self, origin: [f64; 3], dest: [f64; 3]) -> bool { + sculk::is_occluded(origin, dest, |p| { + self.state_is(&self.sculk.tables.occludes, self.world.block(p.x, p.y, p.z)) + }) + } + /// `VibrationSystem.Listener.handleGameEvent` for a sculk block. + fn sculk_listen( + &mut self, + key: (i32, i32, i32), + event: &'static str, + pos: [f64; 3], + ctx: &Context, + ) { + let Some(entity) = self.sculk_entity(key) else { + self.sculk.index.remove(&key); + return; + }; + let (kind, radius, busy) = ( + entity.kind, + entity.listener_radius(), + entity.vibration.current.is_some(), + ); + if kind == SculkKind::Catalyst || busy { + return; + } + let source_block = block_of(pos); + if dist_sqr(source_block, key) > i64::from(radius * radius) { + return; + } + let listens = match kind { + SculkKind::Shrieker => sculk::shrieker_can_listen(event), + _ => sculk::is_vibration(event), + }; + if !sculk::valid_vibration(listens, event, ctx) { + return; + } + let state = self.world.block(key.0, key.1, key.2); + let can_receive = match kind { + SculkKind::Sensor | SculkKind::Calibrated => { + if source_block == [key.0, key.1, key.2] + && matches!(event, "minecraft:block_destroy" | "minecraft:block_place") + { + false + } else if sculk::frequency(event) == 0 + || !self.res.behaviours.sculk_sensor_can_activate(state) + { + false + } else if kind == SculkKind::Calibrated { + let back = self.calibrated_signal(key); + !(back != 0 && sculk::frequency(event) != back) + } else { + true + } + } + SculkKind::Shrieker => !self.shrieker_shrieking(state) && ctx.player, + SculkKind::Catalyst => false, + }; + if !can_receive { + return; + } + let dest = center(key); + if self.occluded(pos, dest) { + return; + } + let distance = { + let d = [pos[0] - dest[0], pos[1] - dest[1], pos[2] - dest[2]]; + (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32 + }; + let time = self.world.game_time; + if let Some(entity) = self.sculk_entity(key) { + entity.vibration.schedule( + Info { + event, + distance, + pos, + source: ctx.source, + owner: ctx.owner, + }, + time, + ); + } + } + fn calibrated_signal(&mut self, key: (i32, i32, i32)) -> i32 { + let pos = BlockPos::new(key.0, key.1, key.2); + let mut value = 0; + self.with_level(|b, level, ticks| { + value = b.calibrated_back_signal(level, ticks, pos); + }); + value + } + fn shrieker_shrieking(&self, state: BlockStateId) -> bool { + self.state_property(state, "shrieking") == Some("true") + } + fn state_property(&self, state: BlockStateId, key: &str) -> Option<&str> { + self.res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get(key)) + .map(String::as_str) + } + + /// `Warden.VibrationUser`: accept a vibration for the warden at `index`. + fn warden_listen(&mut self, index: usize, event: &'static str, pos: [f64; 3], ctx: &Context) { + let now = self.world.game_time; + let (eye, busy) = { + let m = &self.mobs[index]; + let Some(st) = m.extra.warden.as_ref() else { + return; + }; + ( + [m.position.x, m.position.y + m.kind.eye_height, m.position.z], + st.vibration.current.is_some(), + ) + }; + if busy { + return; + } + let source_block = block_of(pos); + let eye_block = block_of(eye); + let d = [ + i64::from(source_block[0]) - i64::from(eye_block[0]), + i64::from(source_block[1]) - i64::from(eye_block[1]), + i64::from(source_block[2]) - i64::from(eye_block[2]), + ]; + if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 256 { + return; + } + if !sculk::valid_vibration(sculk::warden_can_listen(event), event, ctx) { + return; + } + if !warden::can_receive_vibration(&self.mobs[index], i64::from(self.mobs[index].age), ctx) { + return; + } + if self.occluded(pos, eye) { + return; + } + let distance = { + let d = [pos[0] - eye[0], pos[1] - eye[1], pos[2] - eye[2]]; + (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32 + }; + if let Some(st) = self.mobs[index].extra.warden.as_mut() { + st.vibration.schedule( + Info { + event, + distance, + pos, + source: ctx.source, + owner: ctx.owner, + }, + now, + ); + } + } + + // ---- ticking ---- + + /// The block entities of sculk: vibration tickers and catalysts, then the + /// entity-driven events of this tick. + pub(super) fn tick_sculk(&mut self) -> Result<()> { + self.sculk.ticks = self.sculk.ticks.wrapping_add(1); + self.sculk_prepare(); + self.sculk.tracker.tick(); + self.sculk_sync_index(); + let keys: Vec<(i32, i32, i32)> = self.sculk.index.iter().copied().collect(); + for key in keys { + let ticking = self.chunk_ticks(key.0 >> 4, key.2 >> 4); + if !ticking { + continue; + } + self.tick_sculk_block(key)?; + } + self.sculk_step_on(); + self.tick_entity_events(); + Ok(()) + } + /// `ServerLevel.shouldTickBlocksAt`, as `tick_blocks` decides it. + fn chunk_ticks(&self, cx: i32, cz: i32) -> bool { + let Some(p) = self.player.as_ref() else { + return false; + }; + let (pcx, pcz) = ( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + ); + let simulation = self.settings.render_distance.min(8); + (cx - pcx).abs() <= simulation + && (cz - pcz).abs() <= simulation + && self.world.chunks.get(&(cx, cz)).is_some_and(|c| c.lit) + } + fn tick_sculk_block(&mut self, key: (i32, i32, i32)) -> Result<()> { + let time = self.world.game_time; + let adjacent = (-1..=1) + .all(|dx| (-1..=1).all(|dz| self.chunk_ticks((key.0 >> 4) + dx, (key.2 >> 4) + dz))); + let Some(entity) = self.sculk_entity(key) else { + self.sculk.index.remove(&key); + return Ok(()); + }; + match entity.kind { + SculkKind::Catalyst => { + // SculkCatalystBlockEntity.serverTick. + let mut spreader = std::mem::take(&mut entity.spreader); + if !spreader.cursors.is_empty() { + let origin = BlockPos::new(key.0, key.1, key.2); + self.with_level(|b, level, ticks| { + b.sculk_update_cursors(level, ticks, &mut spreader, origin, true); + }); + self.process_level_events()?; + } + if let Some(e) = self.sculk_entity(key) { + // Cursors added while spreading keep their place. + let added = std::mem::take(&mut e.spreader); + e.spreader = spreader; + for c in added.cursors { + e.spreader.add_cursor(c); + } + } + } + SculkKind::Sensor | SculkKind::Calibrated | SculkKind::Shrieker => { + let tick = entity + .vibration + .tick(time, adjacent, true, |d| d.floor() as i32); + if let Some((info, travel)) = tick.started { + self.vibration_particle(info.pos, center(key), travel); + } + if let Some(info) = tick.received { + self.sculk_receive(key, info)?; + } + } + } + Ok(()) + } + + // ---- sensors ---- + + /// `onReceiveVibration` of a sensor or a shrieker. + fn sculk_receive(&mut self, key: (i32, i32, i32), info: Info) -> Result<()> { + let Some(entity) = self.sculk_entity(key) else { + return Ok(()); + }; + let (kind, radius) = (entity.kind, entity.listener_radius()); + let origin = block_of(info.pos); + let distance = (dist_sqr(origin, key) as f64).sqrt() as f32; + match kind { + SculkKind::Sensor | SculkKind::Calibrated => { + let state = self.world.block(key.0, key.1, key.2); + if self.res.behaviours.sculk_sensor_can_activate(state) { + let frequency = sculk::frequency(info.event); + if let Some(e) = self.sculk_entity(key) { + e.last_frequency = frequency; + } + let power = sculk::redstone_strength(distance, radius); + self.activate_sensor(key, info.source, power, frequency)?; + } + } + SculkKind::Shrieker => { + let by_player = info.owner.or(info.source); + self.try_shriek( + key, + by_player == Some(Who::Player) || self.rides_player(by_player), + )?; + } + SculkKind::Catalyst => {} + } + Ok(()) + } + fn rides_player(&self, who: Option) -> bool { + matches!(who, Some(Who::Mob(id)) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some())) + } + /// `SculkSensorBlock.activate`. + fn activate_sensor( + &mut self, + key: (i32, i32, i32), + source: Option, + power: i32, + frequency: i32, + ) -> Result<()> { + let pos = BlockPos::new(key.0, key.1, key.2); + self.with_level(|b, level, ticks| b.sculk_sensor_activate(level, ticks, pos, power)); + self.process_level_events()?; + // tryResonateVibration. + if (1..=15).contains(&frequency) { + for direction in Direction::ALL { + let n = direction.normal(); + let relative = (key.0 + n[0], key.1 + n[1], key.2 + n[2]); + let state = self.world.block(relative.0, relative.1, relative.2); + if self.state_is(&self.sculk.tables.resonator, state) { + let ctx = self.who_context(source, Some(state)); + self.post_game_event( + sculk::RESONANCE[frequency as usize - 1], + center(relative), + ctx, + ); + self.audio.play( + "minecraft:block.amethyst_block.resonate", + Some(center(relative)), + 1.0, + sculk::resonance_pitch(frequency), + ); + } + } + } + let ctx = self.who_context(source, None); + self.post_game_event(sculk::TENDRILS_CLICKING, center(key), ctx); + self.with_level(|b, level, ticks| b.sculk_sensor_click(level, ticks, pos)); + self.process_level_events() + } + /// `SculkSensorBlock.stepOn` and `SculkShriekerBlock.stepOn`: standing on + /// them is heard (or seen) every tick. + fn sculk_step_on(&mut self) { + let mut standing: Vec<(Who, [f64; 3])> = Vec::new(); + if let Some(p) = self.player.as_ref() + && p.ground.on_ground + { + standing.push((Who::Player, [p.position.x, p.position.y, p.position.z])); + } + for m in &self.mobs { + if m.alive() && m.on_ground { + standing.push((Who::Mob(m.id), [m.position.x, m.position.y, m.position.z])); + } + } + for (who, at) in standing { + // getOnPosLegacy: 0.2 below the feet. + let key = ( + at[0].floor() as i32, + (at[1] - 0.2).floor() as i32, + at[2].floor() as i32, + ); + if !self.sculk.index.contains(&key) { + continue; + } + let state = self.world.block(key.0, key.1, key.2); + let is_warden = matches!(who, Who::Mob(id) + if self.mobs.iter().any(|m| m.id == id && m.species() == Species::Warden)); + match self.kind_of_state(state.0 as u16) { + KIND_SENSOR | KIND_CALIBRATED => { + if is_warden || !self.res.behaviours.sculk_sensor_can_activate(state) { + continue; + } + let calibrated = self.kind_of_state(state.0 as u16) == KIND_CALIBRATED; + if calibrated { + let back = self.calibrated_signal(key); + if back != 0 && back != 1 { + continue; + } + } + let dest = center(key); + let d = [at[0] - dest[0], at[1] - dest[1], at[2] - dest[2]]; + let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; + let time = self.world.game_time; + if let Some(e) = self.sculk_entity(key) { + e.vibration.schedule( + Info { + event: "minecraft:step", + distance, + pos: at, + source: Some(who), + owner: None, + }, + time, + ); + } + } + KIND_SHRIEKER => { + let by_player = who == Who::Player || self.rides_player(Some(who)); + if by_player { + let _ = self.try_shriek(key, true); + } + } + _ => {} + } + } + } + + // ---- shriekers ---- + + fn can_respond(&self, state: BlockStateId) -> bool { + use horizon_world::food::Difficulty; + self.state_property(state, "can_summon") == Some("true") + && self.world.health_rules.difficulty != Difficulty::Peaceful + && self.ui.rules.bool("spawn_wardens") + } + /// `SculkShriekerBlockEntity.tryShriek`. + fn try_shriek(&mut self, key: (i32, i32, i32), by_player: bool) -> Result<()> { + if !by_player { + return Ok(()); + } + let state = self.world.block(key.0, key.1, key.2); + if self.shrieker_shrieking(state) { + return Ok(()); + } + if let Some(e) = self.sculk_entity(key) { + e.warning_level = 0; + } + if !self.can_respond(state) || self.try_to_warn(key) { + self.shriek(key)?; + } + Ok(()) + } + /// `WardenSpawnTracker.tryWarn` for the one player. + fn try_to_warn(&mut self, key: (i32, i32, i32)) -> bool { + let c = center(key); + let warden_nearby = self.mobs.iter().any(|m| { + m.species() == Species::Warden + && m.alive() + && (m.position.x - c[0]).abs() < 24.0 + && (m.position.y + f64::from(m.height()) / 2.0 - c[1]).abs() < 24.0 + && (m.position.z - c[2]).abs() < 24.0 + }); + let near = self.player.as_ref().is_some_and(|p| { + !self.spectator() + && !p.health.dead_or_dying() + && (p.position.x - c[0]).powi(2) + + (p.position.y - c[1]).powi(2) + + (p.position.z - c[2]).powi(2) + < WardenSpawnTracker::PLAYER_SEARCH_RADIUS.powi(2) + }); + // The triggering player is always among them. + let _ = near; + let mut trackers = [self.sculk.tracker]; + let level = WardenSpawnTracker::try_warn(&mut trackers, warden_nearby); + self.sculk.tracker = trackers[0]; + match level { + Some(level) => { + if let Some(e) = self.sculk_entity(key) { + e.warning_level = level; + } + true + } + None => false, + } + } + /// `SculkShriekerBlockEntity.shriek`. + fn shriek(&mut self, key: (i32, i32, i32)) -> Result<()> { + let pos = BlockPos::new(key.0, key.1, key.2); + self.with_level(|b, level, ticks| b.sculk_shrieker_shriek(level, ticks, pos)); + self.process_level_events()?; + let ctx = self.player_context(None); + self.post_game_event(sculk::SHRIEK, center(key), ctx); + Ok(()) + } + /// The shriek ended (or the block went away while shrieking). + pub(super) fn shrieker_respond( + &mut self, + key: (i32, i32, i32), + state: BlockStateId, + warning: i32, + ) { + if !(self.can_respond(state) && warning > 0) { + return; + } + if !self.try_summon_warden(key, warning) { + self.warden_reply_sound(key, warning); + } + self.apply_darkness(center(key), 40.0); + } + /// A `shrieker_respond` block event. + pub(super) fn shrieker_block_event(&mut self, pos: BlockPos, state: BlockStateId) { + let key = (pos.x, pos.y, pos.z); + let warning = self.sculk_entity(key).map_or(0, |e| e.warning_level); + self.shrieker_respond(key, state, warning); + } + fn warden_reply_sound(&mut self, key: (i32, i32, i32), warning: i32) { + let sound = match warning { + 1 => "minecraft:entity.warden.nearby_close", + 2 => "minecraft:entity.warden.nearby_closer", + 3 => "minecraft:entity.warden.nearby_closest", + 4 => "minecraft:entity.warden.listening_angry", + _ => return, + }; + let r = &mut self.world.random; + let mut offset = |v: i32| v + r.next_int_bound(21).unwrap_or(0) - 10; + let at = [ + f64::from(offset(key.0)), + f64::from(offset(key.1)), + f64::from(offset(key.2)), + ]; + self.audio.play(sound, Some(at), 5.0, 1.0); + } + /// `SpawnUtil.trySpawnMob` for a warden around the shrieker. + fn try_summon_warden(&mut self, key: (i32, i32, i32), warning: i32) -> bool { + if warning < 4 { + return false; + } + for _ in 0..20 { + let r = &mut self.world.random; + let dx = r.next_int_bound(11).unwrap_or(0) - 5; + let dz = r.next_int_bound(11).unwrap_or(0) - 5; + let Some(at) = self.spawn_position(key.0 + dx, key.1 + 6, key.2 + dz, 6) else { + continue; + }; + let spot = [ + f64::from(at.0) + 0.5, + f64::from(at.1), + f64::from(at.2) + 0.5, + ]; + if !self.warden_fits(spot) { + continue; + } + let Some(id) = self.spawn_mob("minecraft:warden", spot, false) else { + continue; + }; + let mut events = Vec::new(); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + warden::finalize(m, true, &mut events); + } + let _ = self.handle_mob_events(events); + return true; + } + false + } + /// `SpawnUtil.moveToPossibleSpawnPosition` with `ON_TOP_OF_COLLIDER`. + fn spawn_position(&self, x: i32, y: i32, z: i32, range: i32) -> Option<(i32, i32, i32)> { + use horizon_client::mobs::data; + let flags = |b: BlockStateId| self.res.mob_data.state(b); + let mut search = y; + let mut above = self.world.block(x, search, z); + for _ in (-range..=range).rev() { + search -= 1; + let current = self.world.block(x, search, z); + let empty_above = flags(above).top == 0.0; + let full_top = flags(current).flags & data::STURDY_TOP != 0; + if empty_above && full_top { + return Some((x, search + 1, z)); + } + above = current; + } + None + } + /// `Warden.checkSpawnObstruction`: no liquid and no collision in its box. + fn warden_fits(&self, at: [f64; 3]) -> bool { + use horizon_core::geometry::{Aabb, Vec3}; + let Some(kind) = self.res.mob_types.get("minecraft:warden") else { + return false; + }; + let half = kind.width / 2.0; + let bounds = Aabb::new( + Vec3::new(at[0] - half, at[1], at[2] - half), + Vec3::new(at[0] + half, at[1] + kind.height, at[2] + half), + ); + let others: Vec = Vec::new(); + let w = self.mob_world_base(&others); + let min = [ + bounds.min_position().x, + bounds.min_position().y, + bounds.min_position().z, + ]; + let max = [ + bounds.max_position().x, + bounds.max_position().y, + bounds.max_position().z, + ]; + for x in min[0].floor() as i32..=max[0].floor() as i32 { + for y in min[1].floor() as i32..=max[1].floor() as i32 { + for z in min[2].floor() as i32..=max[2].floor() as i32 { + if w.fluid(x, y, z) != horizon_client::blocks::Fluid::None { + return false; + } + } + } + } + w.no_collision(bounds) + } + + // ---- darkness ---- + + /// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`. + pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) { + if self.creative || self.spectator() { + return; + } + let Some(p) = self.player.as_ref() else { + return; + }; + let d = [ + p.position.x - at[0], + p.position.y - at[1], + p.position.z - at[2], + ]; + if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] >= radius * radius { + return; + } + if let Some(active) = self.potions.effects.get("minecraft:darkness") + && active.duration > warden::DARKNESS_REAPPLY - 1 + { + return; + } + let mut effect = + horizon_client::effects::EffectInstance::new("darkness", warden::DARKNESS_DURATION, 0); + effect.visible = false; + self.potions.effects.add(effect); + } + + // ---- catalysts ---- + + /// `SculkCatalystBlockEntity.CatalystListener.handleGameEvent` for the + /// death of a mob: the nearest catalyst within 8 blocks takes its + /// experience. Returns whether it was consumed. + pub(super) fn catalyst_takes_experience( + &mut self, + at: [f64; 3], + experience: impl FnOnce(&mut Self) -> u32, + ) -> bool { + let source = block_of(at); + let mut nearest: Option<((i32, i32, i32), i64)> = None; + for key in self.sculk.index.iter().copied() { + let d = dist_sqr(source, key); + if d <= 64 && nearest.is_none_or(|(_, best)| d < best) { + let is_catalyst = matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Sculk(e)) if e.kind == SculkKind::Catalyst + ); + if is_catalyst { + nearest = Some((key, d)); + } + } + } + let Some((key, _)) = nearest else { + return false; + }; + let xp = experience(self); + if xp > 0 { + // sourcePosition.relative(UP, 0.5) + let start = BlockPos::new(source[0], (at[1] + 0.5).floor() as i32, source[2]); + if let Some(e) = self.sculk_entity(key) { + e.spreader.add_cursors(start, xp as i32); + } + } + self.catalyst_bloom(key); + true + } + fn catalyst_bloom(&mut self, key: (i32, i32, i32)) { + let pos = BlockPos::new(key.0, key.1, key.2); + self.with_level(|b, level, ticks| b.sculk_catalyst_bloom(level, ticks, pos)); + let _ = self.process_level_events(); + let c = center(key); + let options = ParticleOptions::simple(ParticleType::SculkSoul); + for _ in 0..2 { + let r = &mut self.world.random; + let p = [ + c[0] + r.next_gaussian() * 0.2, + c[1] + 0.65, + c[2] + r.next_gaussian() * 0.2, + ]; + self.particles.add(&options, p, [0.0; 3]); + } + let pitch = 0.6 + self.world.random.next_float() * 0.4; + self.audio + .play("minecraft:block.sculk_catalyst.bloom", Some(c), 2.0, pitch); + } + + // ---- particles ---- + + /// `LevelEvent` 3006: charge cursors moving over sculk, or popping. + pub(super) fn sculk_charge_event(&mut self, pos: BlockPos, data: i32) { + let c = center((pos.x, pos.y, pos.z)); + let count = data >> 6; + if count > 0 { + let r = &mut self.world.random; + if r.next_float() < 0.3 + count as f32 * 0.1 { + let volume = 0.15 + 0.02 * (count * count) as f32 * r.next_float(); + let pitch = 0.4 + 0.3 * count as f32 * r.next_float(); + self.audio + .play("minecraft:block.sculk.charge", Some(c), volume, pitch); + } + let face_data = data & 63; + let faces: Vec<(Direction, f32, f64)> = if face_data == 0 { + Direction::ALL + .into_iter() + .map(|d| { + let roll = if d == Direction::Down { + std::f32::consts::PI + } else { + 0.0 + }; + let factor = if matches!(d, Direction::Up | Direction::Down) { + 0.65 + } else { + 0.57 + }; + (d, roll, factor) + }) + .collect() + } else { + horizon_world::level::sculk::unpack_faces(face_data) + .into_iter() + .map(|d| { + let roll = if d == Direction::Up { + std::f32::consts::PI + } else { + 0.0 + }; + (d, roll, 0.35) + }) + .collect() + }; + for (direction, roll, factor) in faces { + let repetitions = self.world.random.next_int_bound(count + 1).unwrap_or(0); + for _ in 0..repetitions { + self.spawn_particle_on_face(pos, direction, roll, factor); + } + } + } else { + self.audio + .play("minecraft:block.sculk.charge", Some(c), 1.0, 1.0); + let solid = self + .res + .facts + .get(self.world.block(pos.x, pos.y, pos.z)) + .full_collision; + let (particles, spread) = if solid { (40, 0.45f32) } else { (20, 0.25f32) }; + let options = ParticleOptions::simple(ParticleType::SculkChargePop); + for _ in 0..particles { + let r = &mut self.world.random; + let v = [ + 2.0 * r.next_float() - 1.0, + 2.0 * r.next_float() - 1.0, + 2.0 * r.next_float() - 1.0, + ]; + let at = [ + c[0] + f64::from(v[0] * spread), + c[1] + f64::from(v[1] * spread), + c[2] + f64::from(v[2] * spread), + ]; + let speed = [ + f64::from(v[0] * 0.07), + f64::from(v[1] * 0.07), + f64::from(v[2] * 0.07), + ]; + self.particles.add(&options, at, speed); + } + } + } + /// `ParticleUtils.spawnParticleOnFace` for a sculk charge. + fn spawn_particle_on_face(&mut self, pos: BlockPos, face: Direction, roll: f32, factor: f64) { + let c = center((pos.x, pos.y, pos.z)); + let step = face.normal(); + let r = &mut self.world.random; + let mut jitter = || r.next_double() - 0.5; + let mut at = [0.0; 3]; + for i in 0..3 { + at[i] = c[i] + + if step[i] == 0 { + jitter() + } else { + f64::from(step[i]) * factor + }; + } + let mut speed = [0.0; 3]; + for i in 0..3 { + let s = (r.next_double() * 2.0 - 1.0) * f64::from(0.005f32); + speed[i] = if step[i] == 0 { s } else { 0.0 }; + } + self.particles + .add(&ParticleOptions::sculk_charge(roll), at, speed); + } + /// `LevelEvent` 3007: ten shrieks rising from the shrieker, and the shriek. + pub(super) fn shriek_event(&mut self, pos: BlockPos) { + let top = f64::from(pos.y) + 0.5; + for i in 0..10 { + self.particles.add( + &ParticleOptions::shriek(i * 5), + [f64::from(pos.x) + 0.5, top, f64::from(pos.z) + 0.5], + [0.0; 3], + ); + } + let state = self.world.block(pos.x, pos.y, pos.z); + if self.state_property(state, "waterlogged") != Some("true") { + let pitch = 0.6 + self.world.random.next_float() * 0.4; + self.audio.play( + "minecraft:block.sculk_shrieker.shriek", + Some([f64::from(pos.x) + 0.5, top, f64::from(pos.z) + 0.5]), + 2.0, + pitch, + ); + } + } + + fn vibration_particle(&mut self, from: [f64; 3], to: [f64; 3], ticks: i32) { + self.particles.vibration(from, to, ticks); + } + /// A vibration travelling to a warden (`MobEvent::Vibration`). + pub(super) fn mob_vibration_particle(&mut self, from: [f64; 3], to: [f64; 3], ticks: i32) { + self.vibration_particle(from, to, ticks); + } + /// `Warden.clientDiggingParticles`: thirty crumbs of the block underfoot. + pub(super) fn warden_dig_particles(&mut self, at: [f64; 3]) { + let below = ( + at[0].floor() as i32, + (at[1] - 0.2).floor() as i32, + at[2].floor() as i32, + ); + let state = self.world.block(below.0, below.1, below.2); + let Some((sprite, tint)) = self.particle_sprite(state) else { + return; + }; + for _ in 0..30 { + let r = &mut self.world.random; + let off = |v: f32| f64::from(v * 1.4 - 0.7); + let p = [ + at[0] + off(r.next_float()), + at[1], + at[2] + off(r.next_float()), + ]; + let particle = + horizon_client::particles::Particle::terrain(r, p, [0.0; 3], sprite.clone(), tint); + self.particles.push(particle); + } + } + + // ---- entity events ---- + + /// Events from entities moving, getting hurt and dying, derived from what + /// changed this tick. + fn tick_entity_events(&mut self) { + // The player. + let player = self.player.as_ref().map(|p| { + ( + [p.position.x, p.position.y, p.position.z], + p.ground.on_ground, + p.health.health(), + p.flying, + ) + }); + if let Some((at, on_ground, health, flying)) = player { + let crouch = self.keys.contains(&KeyCode::ShiftLeft); + let in_water = self.in_water_at(at); + self.entity_motion_events( + Who::Player, + at, + on_ground, + in_water, + crouch && on_ground, + flying, + ); + if let Some(last) = self.sculk.last_health + && health < last + { + self.post_entity_event("minecraft:entity_damage", Who::Player); + } + self.sculk.last_health = Some(health); + } + // Mobs. + let snapshot: Vec<(u32, [f64; 3], bool, bool, Species, Option)> = self + .mobs + .iter() + .filter(|m| m.alive()) + .map(|m| { + ( + m.id, + [m.position.x, m.position.y, m.position.z], + m.on_ground, + m.fluids.in_water, + m.species(), + m.last_damage.map(|(_, t)| t), + ) + }) + .collect(); + for (id, at, on_ground, in_water, species, damaged) in snapshot { + let emits = !matches!(species, Species::Shulker); + if emits { + self.entity_motion_events(Who::Mob(id), at, on_ground, in_water, false, false); + } + if let Some(t) = damaged { + let seen = self.sculk.damaged.insert(id, t); + if seen != Some(t) { + self.post_entity_event("minecraft:entity_damage", Who::Mob(id)); + } + } + } + let alive: HashSet = self.mobs.iter().map(|m| m.id).collect(); + self.sculk.damaged.retain(|id, _| alive.contains(id)); + self.sculk.steps.retain(|who, _| match who { + Who::Player => true, + Who::Mob(id) => alive.contains(id), + }); + } + fn in_water_at(&self, at: [f64; 3]) -> bool { + let (x, y, z) = ( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ); + self.res.facts.get(self.world.block(x, y, z)).fluid == horizon_client::blocks::Fluid::Water + } + /// `Entity.move`'s emission: footsteps, swimming, landing and splashes. + fn entity_motion_events( + &mut self, + who: Who, + at: [f64; 3], + on_ground: bool, + in_water: bool, + discrete: bool, + flying: bool, + ) { + let entry = self.sculk.steps.entry(who).or_insert(Steps { + move_dist: 0.0, + next_step: 1.0, + last: at, + on_ground, + in_water, + }); + let previous = *entry; + entry.last = at; + entry.on_ground = on_ground; + entry.in_water = in_water; + let (dx, dy, dz) = ( + at[0] - previous.last[0], + at[1] - previous.last[1], + at[2] - previous.last[2], + ); + // Entity.checkFallDamage: touching down after falling. + if on_ground && (!previous.on_ground || dy < -1.0e-6) && dy < 0.0 && !in_water { + self.post_entity_event("minecraft:hit_ground", who); + } + // Entity.updateInWaterStateAndDoFluidPushing: entering water splashes. + if in_water && !previous.in_water { + self.post_entity_event("minecraft:splash", who); + } + // Player.getMovementEmission. + if flying || discrete { + return; + } + let horizontal = ((dx * dx + dz * dz).sqrt() * f64::from(0.6f32)) as f32; + let block = ( + at[0].floor() as i32, + (at[1] - 0.2).floor() as i32, + at[2].floor() as i32, + ); + let state = self.world.block(block.0, block.1, block.2); + let air = self.res.facts.is_air(state); + let climbable = self + .res + .items + .block_tags + .get("minecraft:climbable") + .is_some_and(|t| t.contains(&*self.res.facts.get(state).name)); + let travelled = if climbable { + ((dx * dx + dy * dy + dz * dz).sqrt() * f64::from(0.6f32)) as f32 + } else { + horizontal + }; + let Some(entry) = self.sculk.steps.get_mut(&who) else { + return; + }; + entry.move_dist += travelled; + if entry.move_dist > entry.next_step && !air { + let steps_on_block = on_ground || climbable; + let move_dist = entry.move_dist; + if steps_on_block { + let warden = matches!(who, Who::Mob(id) + if self.mobs.iter().any(|m| m.id == id && m.species() == Species::Warden)); + entry.next_step = if warden { + // Warden.nextStep + move_dist + 0.55 + } else { + (move_dist as i32).wrapping_add(1) as f32 + }; + if warden { + self.audio + .play("minecraft:entity.warden.step", Some(at), 10.0, 1.0); + } + let ctx = self.who_context(Some(who), Some(state)); + self.post_game_event("minecraft:step", at, ctx); + } else if in_water { + entry.next_step = (move_dist as i32).wrapping_add(1) as f32; + self.post_entity_event("minecraft:swim", who); + } + } + } + /// `LivingEntity.die` with the catalyst's reach: a death event at the + /// mob's position. + pub(super) fn sculk_mob_died(&mut self, m: &Mob) { + let ctx = self.mob_context(m.id, None); + self.post_game_event( + "minecraft:entity_die", + [m.position.x, m.position.y, m.position.z], + ctx, + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn centres_and_blocks_agree() { + assert_eq!(center((1, 2, 3)), [1.5, 2.5, 3.5]); + assert_eq!(block_of([1.5, 2.5, -0.5]), [1, 2, -1]); + assert_eq!(dist_sqr([0, 0, 0], (3, 4, 0)), 25); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 4d9ef4fbc..51745d4e9 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -55,6 +55,7 @@ pub mod pose; pub mod projectiles; pub mod save; pub mod screen_effects; +pub mod sculk; pub mod settings; pub mod shadows; pub mod signs; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a15b1e1c6..92f4bb799 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -37,6 +37,7 @@ pub mod tame; pub mod undead; pub mod vex; pub mod villager; +pub mod warden; pub mod witch; pub mod wither; mod world; @@ -336,6 +337,7 @@ pub enum DamageKind { Generic, InWall, Thorns, + SonicBoom, } /// A damage source: its type, the attacking entity and where it came from. #[derive(Clone, Copy, Debug)] @@ -390,6 +392,7 @@ impl Damage { | DamageKind::Magic | DamageKind::InWall | DamageKind::Generic + | DamageKind::SonicBoom ) } pub fn is_fire(&self) -> bool { @@ -473,6 +476,8 @@ pub struct Extra { pub meeting: Option<[i32; 3]>, /// Villager and wandering trader offers and experience. pub trade: Option>, + /// A warden's brain, anger and vibrations. + pub warden: Option>, } #[derive(Clone, Debug)] pub struct Mob { @@ -662,6 +667,21 @@ pub enum MobEvent { table: &'static str, at: [f64; 3], }, + /// A vibration travelling to a listener (`VibrationParticleOption`). + Vibration { + from: [f64; 3], + to: [f64; 3], + ticks: i32, + }, + /// The crumbs of the block under a digging or emerging warden. + DigParticles { + at: [f64; 3], + }, + /// `Warden.applyDarknessAround`: darkness for survival players nearby. + Darkness { + at: [f64; 3], + radius: f64, + }, } /// How a spawned-by-kind mob should be set up. #[derive(Clone, Debug, Default)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index d7a9e0084..a6b788c4b 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -87,6 +87,7 @@ pub enum Family { Wither, Allay, Villager, + Warden, } pub fn family(s: Species) -> Family { use Species as S; @@ -130,6 +131,7 @@ pub fn family(s: Species) -> Family { S::Enderman => Family::Enderman, S::Slime | S::MagmaCube => Family::Cube, S::Guardian | S::ElderGuardian => Family::Guardian, + S::Warden => Family::Warden, S::Shulker => Family::Shulker, _ => Family::Generic, } @@ -169,6 +171,7 @@ pub fn register(m: &mut Mob) { Family::Wither => super::wither::register(m), Family::Allay => super::allay::register(m), Family::Villager => super::villager::register(m), + Family::Warden => super::warden::register(m), } } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). @@ -371,6 +374,11 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let sound = match m.species() { + // Warden.getAmbientSound: by anger, silent while roaring or digging. + Species::Warden => match super::warden::ambient_sound(m) { + Some(sound) => sound, + None => return, + }, Species::Zombie | Species::Husk if m.is_baby() => m.kind.sounds[0], Species::Drowned if m.fluids.in_water => "entity.drowned.ambient_water", Species::Enderman if m.ai.target.is_some() => "entity.enderman.scream", @@ -532,6 +540,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { Species::Enderman => super::enderman::custom_server_ai_step(m, cx), Species::Blaze => super::nether::blaze_server_ai_step(m, cx), Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx), + Species::Warden => super::warden::server_ai_step(m, cx), // SpellcasterIllager.customServerAiStep. Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1, _ => {} @@ -559,6 +568,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Zoglin if m.extra.anim_ticks > 0 => m.extra.anim_ticks -= 1, s if super::equine::is_equine(s) => super::equine::ai_step(m, w, events), Species::Phantom => super::phantom::flap_sound(m, events), + Species::Warden => super::warden::ai_step(m, events), Species::Guardian | Species::ElderGuardian => super::guardian::ai_step(m, w, events), Species::Vex => super::vex::ai_step(m, w), Species::Ravager => super::ravager::ai_step(m, w, events), @@ -625,6 +635,7 @@ pub fn speed_bonus(m: &Mob) -> f64 { pub fn sound_volume(m: &Mob) -> f32 { match m.species() { Species::Ghast => 5.0, + Species::Warden => 4.0, Species::Slime | Species::MagmaCube => 0.4 * m.extra.size.max(1) as f32, Species::Cod | Species::Salmon @@ -665,6 +676,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { // Allay.hurtServer: its liked player cannot hurt it. Species::Allay if m.extra.tame && source.attacker == Some(Who::Player) => false, Species::Wither => super::wither::accepts(m, source.kind, source.attacker, false), + Species::Warden => super::warden::accepts_damage(m, source), Species::Shulker => super::shulker::accepts(m, source), Species::Enderman => super::enderman::on_damage(m, source), Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider @@ -681,6 +693,7 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) { match m.species() { Species::Enderman => super::enderman::after_hurt(m, source), Species::Shulker => super::shulker::after_hurt(m), + Species::Warden => super::warden::hurt(m, source), Species::Wolf => super::tame::after_hurt(m, source), // NeutralMob: an iron golem hit by the player stays angry a while. // PiglinAi.wasHurtBy: drop what is being admired, no admiring for diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index f56e504a4..e9a26c79f 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -8,6 +8,7 @@ use std::f32::consts::PI; /// The setupAnim implementation a model uses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Anim { + Warden, Allay, Camel, Wither, @@ -345,6 +346,7 @@ pub fn setup( ) { match m.kind.anim { Anim::Camel => super::camel::anim(m, s, p, w_anims), + Anim::Warden => super::warden::anim(m, s, p, w_anims), Anim::Allay => super::allay::anim(m, s, p), Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => { super::aquatic::anim(m, s, p) diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 327b0662b..2ef75fba6 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -99,6 +99,11 @@ impl Mob { super::species::Baby::None => {} } } + // Warden.getDefaultDimensions: a metre tall while digging or emerging. + if self.kind.species == super::Species::Warden && super::warden::digging_or_emerging(self) { + h = 1.0; + e = 0.85; + } if self.kind.species == super::Species::Pufferfish { let s = super::aquatic::puff_scale(self.extra.size); (w, h, e) = (w * s, h * s, e * s); diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 13a24e1a9..18bbb0257 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -766,7 +766,21 @@ pub fn render_with( draw(part, base, &poses, *uv, *color, light, overlay, out); } held_items(m, &model, base, &poses, atlas, light, out); - for layer in layers(m) { + let mut all_layers = layers(m); + // WardenRenderer: the translucent emissive layers fade with the animations. + if m.species() == Species::Warden { + for (model, texture, a) in super::warden::emissive_layers(m, alpha) { + if a > 0.0 { + all_layers.push(Layer { + model: model.into(), + texture: texture.into(), + color: ((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | 0x00FF_FFFF, + full_bright: true, + }); + } + } + } + for layer in all_layers { let Some(part) = m.kind.layer(&layer.model).cloned() else { continue; }; diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 1138649b2..462a18203 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -292,6 +292,8 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) { Climate::Cold => 2, }; match m.species() { + // Warden.finalizeSpawn: a minute before it digs back down. + S::Warden => super::warden::finalize(m, false, &mut Vec::new()), S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index, S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random), S::Mooshroom => m.extra.variant = 0, diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 820006f32..7d14bdc17 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -83,6 +83,7 @@ pub enum Species { Wither, Camel, Allay, + Warden, } /// Baby bounding boxes (each class's BABY_DIMENSIONS). #[derive(Clone, Copy, Debug)] @@ -1148,6 +1149,20 @@ pub const ALL: &[Def] = &[ Some("entity.strider.step"), Baby::Abs(0.45, 0.85, 0.4375) ), + def!( + Warden, + "warden", + "warden#main", + "entity/warden/warden", + A::Warden, + [ + "entity.warden.ambient", + "entity.warden.hurt", + "entity.warden.death" + ], + None, + Baby::None + ), ]; pub fn def(s: Species) -> &'static Def { ALL.iter().find(|d| d.species == s).unwrap_or(&ALL[0]) @@ -1356,6 +1371,7 @@ impl Def { | S::Vex | S::Ravager | S::Wither + | S::Warden ) } /// The item tag Animal.isFood tests. diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs new file mode 100644 index 000000000..c4177e3d8 --- /dev/null +++ b/crates/horizon-client/src/mobs/warden.rs @@ -0,0 +1,1634 @@ +//! The warden (`Warden`, `WardenAi`, `AngerManagement`): a brain with the +//! emerge, dig, roar, fight, investigate, sniff and idle activities, anger +//! kept per entity, vibration listening, the sonic boom, the heartbeat and +//! tendril animations, and digging back into the ground when nothing has +//! disturbed it for a minute. +use super::{ + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, + anim::{Poses, State}, + goals::{Cx, Float}, + keyframes::Animation, + path::{Path, PathType}, +}; +use crate::sculk::{self, Context, Info}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::{collections::HashMap, f32::consts::PI}; + +pub const EMERGE_DURATION: i64 = 134; +pub const ROAR_DURATION: i64 = 84; +const ROAR_SOUND_DELAY: i64 = 25; +const SNIFFING_DURATION: i64 = 84; +const DIGGING_DURATION: i64 = 100; +pub const DIGGING_COOLDOWN: i64 = 1200; +const MELEE_ATTACK_COOLDOWN: i64 = 18; +const SONIC_DURATION: i64 = 60; +const SONIC_SOUND_DELAY: i64 = 34; +const SPEED_IDLING: f64 = 0.5; +const SPEED_INVESTIGATING: f64 = 0.7; +const SPEED_FIGHTING: f64 = 1.2; +const DEFAULT_ANGER: i32 = 35; +const PROJECTILE_ANGER: i32 = 10; +const ON_HURT_ANGER_BOOST: i32 = 20; +const MAX_ANGER: i32 = 150; +const DARKNESS_RADIUS: f64 = 20.0; +/// Darkness lasts 260 ticks and is renewed within the last 200. +pub const DARKNESS_DURATION: i32 = 260; +pub const DARKNESS_REAPPLY: i32 = 200; + +// AnimState keyframe slots. +const ROAR: usize = 0; +const SNIFF: usize = 1; +const EMERGE: usize = 2; +const DIGGING: usize = 3; +const ATTACK: usize = 4; +const SONIC_BOOM: usize = 5; +// AnimState values: tendril and heart animation (ticks, 10 at the start). +const TENDRIL: usize = 0; +const HEART: usize = 1; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum Pose { + #[default] + Standing, + Emerging, + Digging, + Roaring, + Sniffing, +} +impl Pose { + fn code(self) -> i32 { + match self { + Self::Standing => 0, + Self::Emerging => 1, + Self::Digging => 2, + Self::Roaring => 3, + Self::Sniffing => 4, + } + } + fn from_code(code: i32) -> Self { + match code { + 1 => Self::Emerging, + 2 => Self::Digging, + 3 => Self::Roaring, + 4 => Self::Sniffing, + _ => Self::Standing, + } + } +} +/// The warden's pose (kept in `Extra.counter` so it can be read while the +/// brain is being ticked). +pub fn pose(m: &Mob) -> Pose { + Pose::from_code(m.extra.counter) +} +pub fn digging_or_emerging(m: &Mob) -> bool { + matches!(pose(m), Pose::Digging | Pose::Emerging) +} +/// `Entity.setPose`, with `onSyncedDataUpdated` starting the keyframes. +fn set_pose(m: &mut Mob, new: Pose) { + if pose(m) == new { + return; + } + m.extra.counter = new.code(); + let age = m.age as f32; + match new { + Pose::Emerging => m.anim.states[EMERGE].start(age), + Pose::Digging => m.anim.states[DIGGING].start(age), + Pose::Roaring => m.anim.states[ROAR].start(age), + Pose::Sniffing => m.anim.states[SNIFF].start(age), + Pose::Standing => {} + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AngerLevel { + Calm, + Agitated, + Angry, +} +impl AngerLevel { + pub fn by_anger(anger: i32) -> Self { + if anger >= 80 { + Self::Angry + } else if anger >= 40 { + Self::Agitated + } else { + Self::Calm + } + } + pub fn minimum(self) -> i32 { + match self { + Self::Calm => 0, + Self::Agitated => 40, + Self::Angry => 80, + } + } + pub fn is_angry(self) -> bool { + self == Self::Angry + } + pub fn ambient_sound(self) -> &'static str { + match self { + Self::Calm => "entity.warden.ambient", + Self::Agitated => "entity.warden.agitated", + Self::Angry => "entity.warden.angry", + } + } + pub fn listening_sound(self) -> &'static str { + match self { + Self::Calm => "entity.warden.listening", + _ => "entity.warden.listening_angry", + } + } +} + +/// `AngerManagement`: anger per suspect, highest first. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AngerManagement { + suspects: Vec, + anger: HashMap, + highest: i32, +} +impl AngerManagement { + /// One second: every suspect calms by one; the invalid are forgotten. + pub fn tick(&mut self, valid: impl Fn(Who) -> bool) { + let mut dropped = Vec::new(); + for (who, anger) in self.anger.iter_mut() { + if *anger > 1 && valid(*who) { + *anger -= 1; + } else { + dropped.push(*who); + } + } + for who in dropped { + self.anger.remove(&who); + self.suspects.retain(|s| *s != who); + } + self.sort_and_update_highest(); + } + fn sort_and_update_highest(&mut self) { + // AngerManagement.Sorter: the angry first, then players, then the + // angriest; a stable sort keeps the order of ties. + let anger = self.anger.clone(); + let level = |w: &Who| anger.get(w).copied().unwrap_or(0); + self.suspects.sort_by(|a, b| { + let (aa, ab) = (level(a), level(b)); + let (angry_a, angry_b) = ( + AngerLevel::by_anger(aa).is_angry(), + AngerLevel::by_anger(ab).is_angry(), + ); + if angry_a != angry_b { + return if angry_a { + std::cmp::Ordering::Less + } else { + std::cmp::Ordering::Greater + }; + } + let (player_a, player_b) = (*a == Who::Player, *b == Who::Player); + if player_a != player_b { + return if player_a { + std::cmp::Ordering::Less + } else { + std::cmp::Ordering::Greater + }; + } + ab.cmp(&aa) + }); + self.highest = match self.suspects.len() { + 0 => 0, + 1 => level(&self.suspects[0]), + _ => self.suspects.iter().map(&level).max().unwrap_or(0), + }; + } + /// `increaseAnger`: the entity's new anger (at most 150). + pub fn increase(&mut self, who: Who, amount: i32) -> i32 { + let new_suspect = !self.anger.contains_key(&who); + let current = (self.anger.get(&who).copied().unwrap_or(0) + amount).min(MAX_ANGER); + self.anger.insert(who, current); + if new_suspect { + self.suspects.push(who); + } + self.sort_and_update_highest(); + current + } + pub fn clear(&mut self, who: Who) { + self.anger.remove(&who); + self.suspects.retain(|s| *s != who); + self.sort_and_update_highest(); + } + /// `getActiveAnger`: the target's anger, or the highest when there is none. + pub fn active_anger(&self, target: Option) -> i32 { + match target { + None => self.highest, + Some(t) => self.anger.get(&t).copied().unwrap_or(0), + } + } + /// `getActiveEntity`: the first suspect that can still be targeted. + pub fn active_entity(&self, can_target: impl Fn(Who) -> bool) -> Option { + self.suspects.iter().copied().find(|w| can_target(*w)) + } + pub fn anger_of(&self, who: Who) -> i32 { + self.anger.get(&who).copied().unwrap_or(0) + } + pub fn suspects(&self) -> &[Who] { + &self.suspects + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Activity { + Emerge, + Dig, + Roar, + Fight, + Investigate, + Sniff, + Idle, +} +#[derive(Clone, Copy, Debug, PartialEq)] +enum Track { + Block([i32; 3]), + /// An entity, tracked at its eyes when the flag is set. + Entity(Who, bool), +} +#[derive(Clone, Copy, Debug, PartialEq)] +struct Walk { + target: Track, + speed: f32, + close_enough: i32, +} +/// `MoveToTargetSink`'s running state. +#[derive(Clone, Debug, Default)] +struct MoveSink { + end: i64, + last_target: [i32; 3], + speed: f32, + path: Option, +} +/// `RunOne` over the idle stroll and `DoNothing`. +#[derive(Clone, Copy, Debug, Default)] +struct Pause { + end: i64, +} + +/// The warden's brain and sensors. +#[derive(Clone, Debug)] +pub struct Warden { + pub anger: AngerManagement, + pub vibration: sculk::Data, + activity: Activity, + in_brain: bool, + // Memories: the game time they stop being present (None: absent). + dig_cooldown: Option, + is_emerging: Option, + sniffing: bool, + sniff_cooldown: Option, + roar_target: Option, + attack_target: Option, + disturbance: Option<([i32; 3], i64)>, + look: Option<(Track, i64)>, + walk: Option, + cant_reach_since: Option, + vibration_cooldown: Option, + touch_cooldown: Option, + recent_projectile: Option, + roar_sound_delay: Option, + roar_sound_cooldown: Option, + sonic_cooldown: Option, + sonic_sound_delay: Option, + sonic_sound_cooldown: Option, + attack_cooling_down: Option, + nearest_living: Vec, + nearest_attackable: Option, + sensor_timer: i32, + // Running behaviours (the game time they time out). + emerging: Option, + digging: Option, + roaring: Option, + sniffing_run: Option, + sonic: Option, + look_sink: Option, + move_sink: Option, + move_cooldown: i32, + pause: Option, + /// `getClientAngerLevel`, synchronised once a second. + pub client_anger: i32, + /// Attackers noted by `hurtServer` and not yet handled by the brain. + hurt_by: Vec<(Option, bool)>, +} +const NEVER: i64 = i64::MAX; +impl Default for Warden { + fn default() -> Self { + Self { + anger: AngerManagement::default(), + vibration: sculk::Data::default(), + activity: Activity::Idle, + in_brain: false, + dig_cooldown: None, + is_emerging: None, + sniffing: false, + sniff_cooldown: None, + roar_target: None, + attack_target: None, + disturbance: None, + look: None, + walk: None, + cant_reach_since: None, + vibration_cooldown: None, + touch_cooldown: None, + recent_projectile: None, + roar_sound_delay: None, + roar_sound_cooldown: None, + sonic_cooldown: None, + sonic_sound_delay: None, + sonic_sound_cooldown: None, + attack_cooling_down: None, + nearest_living: Vec::new(), + nearest_attackable: None, + sensor_timer: 0, + emerging: None, + digging: None, + roaring: None, + sniffing_run: None, + sonic: None, + look_sink: None, + move_sink: None, + move_cooldown: 0, + pause: None, + client_anger: 0, + hurt_by: Vec::new(), + } + } +} +fn present(memory: Option, now: i64) -> bool { + memory.is_some_and(|until| now < until) +} +impl Warden { + /// `Brain.setMemoryWithExpiry`: present for `ttl` brain ticks; set + /// outside the brain's tick it loses the one it ticks at once. + fn expiry(&self, now: i64, ttl: i64) -> Option { + Some(now + ttl - i64::from(!self.in_brain)) + } + pub fn target(&self) -> Option { + self.attack_target + } +} + +pub fn register(m: &mut Mob) { + m.extra.warden = Some(Box::default()); + m.ai.nav.can_float = true; + m.set_malus(PathType::UnpassableRail, 0.0); + m.set_malus(PathType::Damaging, 8.0); + m.set_malus(PathType::PowderSnow, 8.0); + m.set_malus(PathType::Lava, 8.0); + m.set_malus(PathType::Fire, 0.0); + m.set_malus(PathType::FireInNeighbor, 0.0); + // Swim(0.8) is part of the brain's core activity. + m.ai.goals.add(0, Float); + // The sensors scan on a random phase. + let phase = m.random.next_int_bound(20).unwrap_or(0); + if let Some(w) = m.extra.warden.as_mut() { + w.sensor_timer = phase; + } +} +/// `Warden.finalizeSpawn`: a minute until it digs back down; a summoned +/// warden climbs out of the ground first. +pub fn finalize(m: &mut Mob, triggered: bool, events: &mut Vec) { + let now = i64::from(m.age); + let Some(st) = m.extra.warden.as_mut() else { + return; + }; + st.dig_cooldown = Some(now + DIGGING_COOLDOWN); + if triggered { + st.is_emerging = Some(now + EMERGE_DURATION); + set_pose(m, Pose::Emerging); + sound(m, "entity.warden.agitated", 5.0, 1.0, events); + } +} +fn at(m: &Mob) -> [f64; 3] { + [m.position.x, m.position.y, m.position.z] +} +fn sound(m: &Mob, name: &'static str, volume: f32, pitch: f32, events: &mut Vec) { + events.push(MobEvent::Sound(name, at(m), volume, pitch)); +} +/// `LivingEntity.getVoicePitch` for an adult. +fn voice_pitch(m: &mut Mob) -> f32 { + (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0 +} +fn closer_than(m: &Mob, p: Vec3, horizontal: f64, vertical: f64) -> bool { + let (dx, dy, dz) = (p.x - m.position.x, p.y - m.position.y, p.z - m.position.z); + dx * dx + dz * dz < horizontal * horizontal && dy.abs() < vertical +} + +// ---- entity facts ---- + +/// `Warden.canTargetEntity`. +pub fn can_target(w: &MobWorld, who: Who) -> bool { + match who { + Who::Player => w.player.as_ref().is_some_and(|p| p.alive && !p.creative), + Who::Mob(id) => w + .seen(id) + .is_some_and(|s| s.alive && s.species != Species::Warden), + } +} +fn position_of(w: &MobWorld, who: Who) -> Option { + w.target_info(who).map(|t| t.position) +} +fn track_position(w: &MobWorld, track: Track) -> Option<[f64; 3]> { + match track { + Track::Block(p) => Some([ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ]), + Track::Entity(who, eyes) => w.target_info(who).map(|t| { + [ + t.position.x, + if eyes { t.eye_y } else { t.position.y }, + t.position.z, + ] + }), + } +} +fn track_block(w: &MobWorld, track: Track) -> Option<[i32; 3]> { + match track { + Track::Block(p) => Some(p), + Track::Entity(who, _) => w.target_info(who).map(|t| { + [ + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ] + }), + } +} +fn block_pos(m: &Mob) -> [i32; 3] { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.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]) -> f64 { + (0..3).map(|i| f64::from(a[i] - b[i]).powi(2)).sum() +} + +// ---- anger ---- + +/// `Warden.increaseAngerAt`. +fn increase_anger( + m: &mut Mob, + st: &mut Warden, + w: &MobWorld, + who: Option, + amount: i32, + play_sound: bool, + events: &mut Vec, +) { + let Some(who) = who else { return }; + if !can_target(w, who) { + return; + } + set_dig_cooldown(st, i64::from(m.age)); + let maybe_switch = st.attack_target != Some(Who::Player); + let new = st.anger.increase(who, amount); + if who == Who::Player && maybe_switch && AngerLevel::by_anger(new).is_angry() { + st.attack_target = None; + } + if play_sound && pose(m) != Pose::Roaring { + let level = angry_level(st); + let pitch = voice_pitch(m); + sound(m, level.listening_sound(), 10.0, pitch, events); + } +} +fn angry_level(st: &Warden) -> AngerLevel { + AngerLevel::by_anger(st.anger.active_anger(st.attack_target)) +} +/// `Warden.getEntityAngryAt`. +fn entity_angry_at(st: &Warden, w: &MobWorld) -> Option { + if angry_level(st).is_angry() { + st.anger.active_entity(|e| can_target(w, e)) + } else { + None + } +} +/// `Warden.getAngerLevel` of a warden (for its ambient sound). +pub fn anger_level(m: &Mob) -> AngerLevel { + m.extra.warden.as_ref().map_or(AngerLevel::Calm, |s| { + AngerLevel::by_anger(s.anger.active_anger(s.attack_target)) + }) +} +/// `WardenAi.setDigCooldown`. +fn set_dig_cooldown(st: &mut Warden, now: i64) { + if present(st.dig_cooldown, now) { + st.dig_cooldown = st.expiry(now, DIGGING_COOLDOWN); + } +} +/// `WardenAi.setDisturbanceLocation`. +fn set_disturbance(st: &mut Warden, w: &MobWorld, now: i64, position: [i32; 3]) { + if entity_angry_at(st, w).is_none() && st.attack_target.is_none() { + set_dig_cooldown(st, now); + st.sniff_cooldown = st.expiry(now, 100); + let until = st.expiry(now, 100).unwrap_or(now); + st.look = Some((Track::Block(position), until)); + st.disturbance = Some((position, until)); + st.walk = None; + } +} +/// `Warden.setAttackTarget`. +fn set_attack_target(st: &mut Warden, target: Who, now: i64) { + st.roar_target = None; + st.attack_target = Some(target); + st.cant_reach_since = None; + st.sonic_cooldown = st.expiry(now, 200); +} + +// ---- damage ---- + +/// `Warden.isInvulnerableTo`: while digging or emerging. +pub fn accepts_damage(m: &Mob, source: &Damage) -> bool { + !(digging_or_emerging(m) && source.kind != DamageKind::Generic) +} +/// `Warden.hurtServer`'s reaction, handled by the brain's next tick. +pub fn hurt(m: &mut Mob, source: &Damage) { + if digging_or_emerging(m) { + return; + } + let direct = !matches!( + source.kind, + DamageKind::Arrow | DamageKind::Thrown | DamageKind::Fireball + ); + if let Some(st) = m.extra.warden.as_mut() { + st.hurt_by.push((source.attacker, direct)); + } +} + +// ---- vibrations ---- + +/// `Warden.VibrationUser.canReceiveVibration`. +pub fn can_receive_vibration(m: &Mob, now: i64, ctx: &Context) -> bool { + let Some(st) = m.extra.warden.as_ref() else { + return false; + }; + m.alive() + && !present(st.vibration_cooldown, now) + && !digging_or_emerging(m) + && !(ctx.living && !ctx.targetable) +} +/// `Warden.VibrationUser.onReceiveVibration`. +fn receive_vibration( + m: &mut Mob, + st: &mut Warden, + w: &MobWorld, + info: Info, + events: &mut Vec, +) { + if !m.alive() { + return; + } + let now = i64::from(m.age); + st.vibration_cooldown = st.expiry(now, 40); + // Entity event 61: the tendrils twitch. + m.anim.v[TENDRIL] = 10.0; + let pitch = voice_pitch(m); + sound(m, "entity.warden.tendril_clicks", 5.0, pitch, events); + let origin = [ + info.pos[0].floor() as i32, + info.pos[1].floor() as i32, + info.pos[2].floor() as i32, + ]; + let mut suspicious = origin; + if let Some(owner) = info.owner { + if let Some(p) = position_of(w, owner) + && closer_than_distance(m, p, 30.0) + { + if present(st.recent_projectile, now) { + if can_target(w, owner) + && let Some(t) = w.target_info(owner) + { + suspicious = [ + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ]; + } + increase_anger(m, st, w, Some(owner), DEFAULT_ANGER, true, events); + } else { + increase_anger(m, st, w, Some(owner), PROJECTILE_ANGER, true, events); + } + } + st.recent_projectile = st.expiry(now, 100); + } else { + increase_anger(m, st, w, info.source, DEFAULT_ANGER, true, events); + } + if !angry_level(st).is_angry() { + let active = st.anger.active_entity(|e| can_target(w, e)); + if info.owner.is_some() || active.is_none() || active == info.source { + set_disturbance(st, w, now, suspicious); + } + } +} +fn closer_than_distance(m: &Mob, p: Vec3, distance: f64) -> bool { + m.distance_sqr(p) < distance * distance +} + +// ---- the brain ---- + +/// `Warden.customServerAiStep`: the vibration ticker, the brain, darkness, +/// anger and the activity. +pub fn server_ai_step(m: &mut Mob, cx: &mut Cx) { + let Some(mut st) = m.extra.warden.take() else { + return; + }; + let now = i64::from(m.age); + // Warden.tick: vibrations arrive before the brain thinks. + st.in_brain = false; + if st.dig_cooldown.is_some() && m.custom_name.is_some() { + set_dig_cooldown(&mut st, now); + } + let tick = st + .vibration + .tick(cx.w.game_time, true, false, |d| d.floor() as i32); + if let Some((info, travel)) = tick.started { + let eye = [m.position.x, m.position.y + m.kind.eye_height, m.position.z]; + cx.events.push(MobEvent::Vibration { + from: info.pos, + to: eye, + ticks: travel, + }); + } + if let Some(info) = tick.received { + receive_vibration(m, &mut st, cx.w, info, cx.events); + } + touch_entities(m, &mut st, cx); + handle_hurt(m, &mut st, cx); + st.in_brain = true; + brain_tick(m, &mut st, cx); + st.in_brain = false; + // Warden.customServerAiStep after the brain. + if (i64::from(m.age) + i64::from(m.id)) % 120 == 0 { + cx.events.push(MobEvent::Darkness { + at: [m.position.x, m.position.y, m.position.z], + radius: DARKNESS_RADIUS, + }); + } + if m.age.is_multiple_of(20) { + let w = cx.w; + st.anger.tick(|who| can_target(w, who)); + st.client_anger = st.anger.active_anger(st.attack_target); + } + update_activity(m, &mut st, now); + m.extra.warden = Some(st); +} +/// `Warden.doPush`: touching something angers it (every second). +fn touch_entities(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + if digging_or_emerging(m) || !m.alive() { + return; + } + let now = i64::from(m.age); + if present(st.touch_cooldown, now) { + return; + } + let bounds = m.bounds(); + let mut touched = None; + if let Some(p) = cx.w.player.as_ref() + && p.alive + && !p.spectator + && bounds.intersects(p.bounds) + { + touched = Some(Who::Player); + } + if touched.is_none() { + touched = + cx.w.others + .iter() + .find(|s| s.id != m.id && s.alive && bounds.intersects(s.bounds)) + .map(|s| Who::Mob(s.id)); + } + if let Some(who) = touched { + st.touch_cooldown = st.expiry(now, 20); + increase_anger(m, st, cx.w, Some(who), DEFAULT_ANGER, true, cx.events); + if let Some(t) = cx.w.target_info(who) { + let block = [ + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ]; + set_disturbance(st, cx.w, now, block); + } + } +} +/// The rest of `Warden.hurtServer`. +fn handle_hurt(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + for (attacker, direct) in std::mem::take(&mut st.hurt_by) { + increase_anger( + m, + st, + cx.w, + attacker, + AngerLevel::Angry.minimum() + ON_HURT_ANGER_BOOST, + false, + cx.events, + ); + if st.attack_target.is_none() + && let Some(who) = attacker + && let Some(p) = position_of(cx.w, who) + && (direct || closer_than_distance(m, p, 5.0)) + { + set_attack_target(st, who, i64::from(m.age)); + } + } +} +/// `Brain.setActiveActivityToFirstValid`, erasing the memories of the +/// activity being left. +fn update_activity(m: &mut Mob, st: &mut Warden, now: i64) { + let _ = m; + let next = if present(st.is_emerging, now) { + Activity::Emerge + } else if st.roar_target.is_none() && !present(st.dig_cooldown, now) { + Activity::Dig + } else if st.roar_target.is_some() { + Activity::Roar + } else if st.attack_target.is_some() { + Activity::Fight + } else if st.disturbance.is_some_and(|(_, until)| now < until) { + Activity::Investigate + } else if st.sniffing { + Activity::Sniff + } else { + Activity::Idle + }; + if next != st.activity { + match st.activity { + Activity::Emerge => st.is_emerging = None, + Activity::Roar => st.roar_target = None, + Activity::Fight => st.attack_target = None, + Activity::Investigate => st.disturbance = None, + Activity::Sniff => st.sniffing = false, + Activity::Dig | Activity::Idle => {} + } + st.activity = next; + } +} +fn active(st: &Warden, activity: Activity) -> bool { + st.activity == activity +} +fn brain_tick(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + let now = i64::from(m.age); + // Memories that timed out are forgotten. + if st.disturbance.is_some_and(|(_, until)| now >= until) { + st.disturbance = None; + } + if st.look.is_some_and(|(_, until)| now >= until) { + st.look = None; + } + sense(m, st, cx.w); + start_behaviours(m, st, cx); + tick_behaviours(m, st, cx); +} +/// `WardenEntitySensor` (and `NearestLivingEntitySensor`) every 20 ticks. +fn sense(m: &mut Mob, st: &mut Warden, w: &MobWorld) { + st.sensor_timer -= 1; + if st.sensor_timer > 0 { + return; + } + st.sensor_timer = 20; + let range = m.attrs.follow_range; + let area = m + .bounds() + .inflate(horizon_core::geometry::Vec3::new(range, range, range)); + let mut found: Vec<(Who, f64)> = Vec::new(); + if let Some(p) = w.player.as_ref() + && p.alive + && area.intersects(p.bounds) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + for s in w.others { + if s.id != m.id && s.alive && area.intersects(s.bounds) { + found.push((Who::Mob(s.id), m.distance_sqr(s.position))); + } + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + st.nearest_living = found.into_iter().map(|(who, _)| who).collect(); + let closest = |players: bool| { + st.nearest_living + .iter() + .copied() + .find(|who| can_target(w, *who) && (*who == Who::Player) == players) + }; + let attackable = closest(true).or_else(|| closest(false)); + st.nearest_attackable = attackable; +} +/// `NearestVisibleLivingEntities.contains`. +fn visible(m: &mut Mob, st: &Warden, w: &MobWorld, who: Who) -> bool { + st.nearest_living.contains(&who) && m.sees(w, who) +} + +fn start_behaviours(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + let now = i64::from(m.age); + // Core: SetWardenLookTarget. + if st.attack_target.is_none() { + let target = st + .roar_target + .and_then(|who| track_block(cx.w, Track::Entity(who, true))) + .or(st.disturbance.map(|(p, _)| p)); + if let Some(p) = target { + st.look = Some((Track::Block(p), NEVER)); + } + } + // Dig: Digging. + if active(st, Activity::Dig) + && st.digging.is_none() + && st.attack_target.is_none() + && st.walk.is_none() + && (m.on_ground || m.is_in_liquid()) + { + st.digging = Some(now + DIGGING_DURATION); + if m.on_ground { + set_pose(m, Pose::Digging); + sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); + } else { + sound(m, "entity.warden.agitated", 5.0, 1.0, cx.events); + stop_digging(m, st); + } + } + // Core: LookAtTargetSink. + if st.look_sink.is_none() && st.look.is_some() { + let duration = 45 + i64::from(m.random.next_int_bound(46).unwrap_or(0)); + st.look_sink = Some(now + duration); + } + // Core: MoveToTargetSink. + if st.move_sink.is_none() && st.walk.is_some() { + start_move_sink(m, st, cx); + } + // Emerge: Emerging. + if active(st, Activity::Emerge) + && st.emerging.is_none() + && present(st.is_emerging, now) + && st.walk.is_none() + { + st.emerging = Some(now + EMERGE_DURATION); + set_pose(m, Pose::Emerging); + sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); + } + // SetRoarTarget (investigate, sniff and idle). + if matches!( + st.activity, + Activity::Investigate | Activity::Sniff | Activity::Idle + ) && st.roar_target.is_none() + && st.attack_target.is_none() + && let Some(target) = entity_angry_at(st, cx.w).filter(|t| can_target(cx.w, *t)) + { + st.roar_target = Some(target); + st.cant_reach_since = None; + } + // Investigate: GoToTargetLocation. + if active(st, Activity::Investigate) + && st.attack_target.is_none() + && st.walk.is_none() + && let Some((location, until)) = st.disturbance + && now < until + { + if dist_sqr(location, block_pos(m)) >= 4.0 { + let ox = m.random.next_int_bound(3).unwrap_or(1) - 1; + let oz = m.random.next_int_bound(3).unwrap_or(1) - 1; + let target = [location[0] + ox, location[1], location[2] + oz]; + st.look = Some((Track::Block(target), NEVER)); + st.walk = Some(Walk { + target: Track::Block(target), + speed: SPEED_INVESTIGATING as f32, + close_enough: 2, + }); + } + } + // Sniff: Sniffing. + if active(st, Activity::Sniff) + && st.sniffing_run.is_none() + && st.sniffing + && st.attack_target.is_none() + && st.walk.is_none() + { + st.sniffing_run = Some(now + SNIFFING_DURATION); + sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); + } + // Roar. + if active(st, Activity::Roar) + && st.roaring.is_none() + && let Some(target) = st.roar_target + && st.attack_target.is_none() + { + st.roaring = Some(now + ROAR_DURATION); + st.roar_sound_delay = st.expiry(now, ROAR_SOUND_DELAY); + st.walk = None; + st.look = Some((Track::Entity(target, true), NEVER)); + set_pose(m, Pose::Roaring); + increase_anger(m, st, cx.w, Some(target), 20, false, cx.events); + } + // Fight: the dig cooldown setter. + if active(st, Activity::Fight) { + set_dig_cooldown(st, now); + } + // Idle: TryToSniff. + if active(st, Activity::Idle) + && !present(st.sniff_cooldown, now) + && st.nearest_attackable.is_some() + && st.disturbance.is_none() + { + st.sniffing = true; + let cooldown = 100 + i64::from(m.random.next_int_bound(101).unwrap_or(0)); + st.sniff_cooldown = st.expiry(now, cooldown); + st.walk = None; + set_pose(m, Pose::Sniffing); + } + // Fight: StopAttackingIfTargetInvalid. + if active(st, Activity::Fight) + && let Some(target) = st.attack_target + { + let tired = st.cant_reach_since.is_some_and(|since| now - since > 200); + let valid = can_target(cx.w, target) + && !tired + && cx.w.target_info(target).is_some_and(|t| t.alive) + && angry_level(st).is_angry(); + if !valid { + if !can_target(cx.w, target) { + st.anger.clear(target); + } + set_dig_cooldown(st, now); + st.attack_target = None; + } + } + // Idle: RunOne over the stroll and DoNothing. + if active(st, Activity::Idle) && st.pause.is_none() && !st.sniffing { + run_one(m, st, cx); + } + // Fight: SetEntityLookTarget. + if active(st, Activity::Fight) + && st.look.is_none() + && let Some(target) = st.attack_target + && visible(m, st, cx.w, target) + && position_of(cx.w, target) + .is_some_and(|p| m.distance_sqr(p) <= m.attrs.follow_range * m.attrs.follow_range) + { + st.look = Some((Track::Entity(target, true), NEVER)); + } + // Fight: SetWalkTargetFromAttackTargetIfTargetOutOfReach. + if active(st, Activity::Fight) + && let Some(target) = st.attack_target + { + let in_reach = visible(m, st, cx.w, target) + && cx + .w + .target_info(target) + .is_some_and(|t| m.within_melee_range(&t)); + if in_reach { + st.walk = None; + } else { + st.look = Some((Track::Entity(target, true), NEVER)); + st.walk = Some(Walk { + target: Track::Entity(target, false), + speed: SPEED_FIGHTING as f32, + close_enough: 0, + }); + } + } + // Fight: SonicBoom. + if active(st, Activity::Fight) + && st.sonic.is_none() + && !present(st.sonic_cooldown, now) + && let Some(target) = st.attack_target + && position_of(cx.w, target).is_some_and(|p| closer_than(m, p, 15.0, 20.0)) + { + st.sonic = Some(now + SONIC_DURATION); + st.attack_cooling_down = st.expiry(now, SONIC_DURATION); + st.sonic_sound_delay = st.expiry(now, SONIC_SOUND_DELAY); + m.anim.states[SONIC_BOOM].start(m.age as f32); + sound(m, "entity.warden.sonic_charge", 3.0, 1.0, cx.events); + } + // Fight: MeleeAttack. + if active(st, Activity::Fight) + && !present(st.attack_cooling_down, now) + && let Some(target) = st.attack_target + && visible(m, st, cx.w, target) + && let Some(info) = cx.w.target_info(target) + && m.within_melee_range(&info) + { + st.look = Some((Track::Entity(target, true), NEVER)); + m.swing(); + attack(m, target, cx); + st.attack_cooling_down = st.expiry(now, MELEE_ATTACK_COOLDOWN); + // SonicBoom.setCooldown(this, 40) from doHurtTarget. + st.sonic_cooldown = st.expiry(now, 40); + m.anim.states[ROAR].stop(); + m.anim.states[ATTACK].start(m.age as f32); + } +} +/// `Warden.doHurtTarget`: the hit, its impact sound and the knockback. +fn attack(m: &mut Mob, target: Who, cx: &mut Cx) { + let pitch = voice_pitch(m); + sound(m, "entity.warden.attack_impact", 10.0, pitch, cx.events); + super::ai::do_hurt_target(m, target, cx); + // ATTACK_KNOCKBACK 1.5: half of it, along the warden's facing. + let yaw = m.yaw.to_radians(); + cx.events.push(MobEvent::Push { + target, + velocity: [ + -f64::from(yaw.sin()) * 0.75, + 0.0, + f64::from(yaw.cos()) * 0.75, + ], + }); + m.velocity.x *= 0.6; + m.velocity.z *= 0.6; +} +/// `RunOne`: a stroll (weight 2) or a pause (weight 1), picked by shuffling. +fn run_one(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + let now = i64::from(m.age); + // ShufflingList.shuffle: each entry sorts by -ln(random) / weight. + let stroll_key = -f64::from(m.random.next_float()).ln() / 2.0; + let pause_key = -f64::from(m.random.next_float()).ln(); + let pause_first = pause_key < stroll_key; + let order = if pause_first { + [false, true] + } else { + [true, false] + }; + for stroll in order { + if stroll { + // RandomStroll.stroll(0.5): only when there is no walk target. + if st.walk.is_none() { + st.walk = m.land_random_pos(cx.w, 10, 7).map(|p| Walk { + target: Track::Block([ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]), + speed: SPEED_IDLING as f32, + close_enough: 0, + }); + return; + } + } else { + let duration = 30 + i64::from(m.random.next_int_bound(31).unwrap_or(0)); + st.pause = Some(Pause { + end: now + duration, + }); + return; + } + } +} +fn stop_digging(m: &mut Mob, st: &mut Warden) { + st.digging = None; + // Digging.stop: the warden is removed. + m.removed = true; +} + +fn tick_behaviours(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + let now = i64::from(m.age); + // LookAtTargetSink. + if let Some(end) = st.look_sink { + let keep = now <= end + && st.look.is_some_and(|(track, _)| match track { + Track::Block(_) => true, + Track::Entity(who, _) => visible(m, st, cx.w, who), + }); + if keep { + if let Some((track, _)) = st.look + && let Some(p) = track_position(cx.w, track) + { + m.look_at(p); + } + } else { + st.look_sink = None; + st.look = None; + } + } + // MoveToTargetSink. + tick_move_sink(m, st, cx); + // Emerging. + if let Some(end) = st.emerging + && now > end + { + st.emerging = None; + if pose(m) == Pose::Emerging { + set_pose(m, Pose::Standing); + } + } + // Digging: removed when the time is up. + if let Some(end) = st.digging + && now > end + { + stop_digging(m, st); + } + // Sniffing. + if let Some(end) = st.sniffing_run + && now > end + { + st.sniffing_run = None; + if pose(m) == Pose::Sniffing { + set_pose(m, Pose::Standing); + } + st.sniffing = false; + if let Some(entity) = st.nearest_attackable.filter(|e| can_target(cx.w, *e)) + && let Some(p) = position_of(cx.w, entity) + { + if sniff_close(m, p) { + increase_anger(m, st, cx.w, Some(entity), DEFAULT_ANGER, true, cx.events); + } + if st.disturbance.is_none() { + let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + set_disturbance(st, cx.w, now, block); + } + } + } + // Roar. + if let Some(end) = st.roaring { + if now > end { + st.roaring = None; + if pose(m) == Pose::Roaring { + set_pose(m, Pose::Standing); + } + if let Some(target) = st.roar_target.take() { + set_attack_target(st, target, now); + } + } else if !present(st.roar_sound_delay, now) && !present(st.roar_sound_cooldown, now) { + st.roar_sound_cooldown = st.expiry(now, ROAR_DURATION - ROAR_SOUND_DELAY); + sound(m, "entity.warden.roar", 3.0, 1.0, cx.events); + } + } + // Sonic boom. + if let Some(end) = st.sonic { + if now > end { + st.sonic = None; + st.sonic_cooldown = st.expiry(now, 40); + } else { + tick_sonic_boom(m, st, cx); + } + } + // The idle pause. + if let Some(pause) = st.pause + && now > pause.end + { + st.pause = None; + } +} +/// `Warden.closerThan(entity, 6, 20)` for the sniff. +fn sniff_close(m: &Mob, p: Vec3) -> bool { + closer_than(m, p, 6.0, 20.0) +} +fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + let now = i64::from(m.age); + let Some(target) = st.attack_target else { + return; + }; + if let Some(t) = cx.w.target_info(target) { + m.look_at([t.position.x, t.position.y, t.position.z]); + } + if present(st.sonic_sound_delay, now) || present(st.sonic_sound_cooldown, now) { + return; + } + st.sonic_sound_cooldown = st.expiry(now, SONIC_DURATION - SONIC_SOUND_DELAY); + if !can_target(cx.w, target) { + return; + } + let Some(t) = cx.w.target_info(target) else { + return; + }; + if !closer_than(m, t.position, 15.0, 20.0) { + return; + } + // The chest attachment: 1.6 up and 0.0 forward. + let source = [m.position.x, m.position.y + 1.6, m.position.z]; + let eye = [t.position.x, t.eye_y, t.position.z]; + let delta = [eye[0] - source[0], eye[1] - source[1], eye[2] - source[2]]; + let length = (delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2]).sqrt(); + if length < 1.0e-9 { + return; + } + let normal = [delta[0] / length, delta[1] / length, delta[2] / length]; + let steps = length.floor() as i32 + 7; + for i in 1..steps { + let d = f64::from(i); + cx.events.push(MobEvent::Particles { + kind: "sonic_boom", + at: [ + source[0] + normal[0] * d, + source[1] + normal[1] * d, + source[2] + normal[2] * d, + ], + count: 0, + }); + } + sound(m, "entity.warden.sonic_boom", 3.0, 1.0, cx.events); + let from = at(m); + // Players and the mobs hit here have no knockback resistance. + let resistance = 0.0; + match target { + Who::Player => cx.events.push(MobEvent::DamagePlayer { + amount: 10.0, + from, + kind: "minecraft:sonic_boom", + }), + Who::Mob(id) => cx.events.push(MobEvent::AttackMob { + target: id, + amount: 10.0, + source: Damage { + kind: DamageKind::SonicBoom, + attacker: Some(Who::Mob(m.id)), + from: Some(from), + }, + }), + } + let horizontal = 2.5 * (1.0 - resistance); + let vertical = 0.5 * (1.0 - resistance); + cx.events.push(MobEvent::Push { + target, + velocity: [ + normal[0] * horizontal, + normal[1] * vertical, + normal[2] * horizontal, + ], + }); +} + +// ---- walking: MoveToTargetSink ---- + +fn reached_target(m: &Mob, w: &MobWorld, walk: &Walk) -> bool { + track_block(w, walk.target).is_some_and(|p| manhattan(p, block_pos(m)) <= walk.close_enough) +} +/// `MoveToTargetSink.tryComputePath`. +fn try_compute_path(m: &mut Mob, st: &mut Warden, w: &MobWorld, walk: &Walk) -> Option { + let target = track_block(w, walk.target)?; + let now = i64::from(m.age); + let mut path = m.create_path_to(w, target, 0); + if reached_target(m, w, walk) { + st.cant_reach_since = None; + return None; + } + let can_reach = path.as_ref().is_some_and(|p| p.reached); + if can_reach { + st.cant_reach_since = None; + } else if st.cant_reach_since.is_none() { + st.cant_reach_since = Some(now); + } + if path.is_some() { + return path; + } + let bottom_center = [ + f64::from(target[0]) + 0.5, + f64::from(target[1]), + f64::from(target[2]) + 0.5, + ]; + if let Some(p) = m.land_random_pos_towards(w, 10, 7, bottom_center) { + path = m.create_path_to_entity(w, p, 0); + } + path +} +fn start_move_sink(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + let now = i64::from(m.age); + let Some(walk) = st.walk else { return }; + if st.move_sink.is_some() { + return; + } + if st.move_cooldown > 0 { + st.move_cooldown -= 1; + return; + } + let reached = reached_target(m, cx.w, &walk); + if !reached && let Some(path) = try_compute_path(m, st, cx.w, &walk) { + let duration = 150 + i64::from(m.random.next_int_bound(101).unwrap_or(0)); + let last = track_block(cx.w, walk.target).unwrap_or_default(); + m.nav_move_to_path(Some(path.clone()), f64::from(walk.speed)); + st.move_sink = Some(MoveSink { + end: now + duration, + last_target: last, + speed: walk.speed, + path: Some(path), + }); + return; + } + st.walk = None; + if reached { + st.cant_reach_since = None; + } +} +fn tick_move_sink(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { + let now = i64::from(m.age); + let Some(mut sink) = st.move_sink.take() else { + return; + }; + let walk = st.walk; + let still = now <= sink.end + && walk.is_some_and(|walk| { + let spectator = matches!(walk.target, Track::Entity(Who::Player, _)) + && cx.w.player.as_ref().is_some_and(|p| p.spectator); + !m.ai.nav.is_done() && !reached_target(m, cx.w, &walk) && !spectator + }); + if !still { + // MoveToTargetSink.stop. + if let Some(walk) = walk + && !reached_target(m, cx.w, &walk) + && m.ai.nav.stuck + { + st.move_cooldown = m.random.next_int_bound(40).unwrap_or(0); + } + m.nav_stop(); + st.walk = None; + return; + } + if let Some(walk) = walk + && let Some(target) = track_block(cx.w, walk.target) + && dist_sqr(target, sink.last_target) > 4.0 + && let Some(path) = try_compute_path(m, st, cx.w, &walk) + { + sink.last_target = target; + sink.speed = walk.speed; + m.nav_move_to_path(Some(path.clone()), f64::from(walk.speed)); + sink.path = Some(path); + } + st.move_sink = Some(sink); +} + +// ---- per-tick client behaviour ---- + +/// `Warden.tick` on the client: the heartbeat, the tendrils and the digging +/// crumbs; the keyframe states follow the pose. +pub fn ai_step(m: &mut Mob, events: &mut Vec) { + let Some(st) = m.extra.warden.as_ref() else { + return; + }; + let client_anger = st.client_anger; + let delay = heart_beat_delay(client_anger); + if i64::from(m.age) % i64::from(delay) == 0 { + m.anim.v[HEART] = 10.0; + let pitch = voice_pitch(m); + sound(m, "entity.warden.heartbeat", 5.0, pitch, events); + } + // The animation values count down after the sync of the last tick. + for slot in [TENDRIL, HEART] { + if m.anim.v[slot] > 0.0 { + m.anim.v[slot] -= 1.0; + } + } + let digging_clock = |m: &Mob, slot: usize| { + m.anim.states[slot] + .millis(m.age as f32) + .is_some_and(|ms| (ms as f32) < 4500.0) + }; + match pose(m) { + Pose::Emerging if digging_clock(m, EMERGE) => { + events.push(MobEvent::DigParticles { at: at(m) }) + } + Pose::Digging if digging_clock(m, DIGGING) => { + events.push(MobEvent::DigParticles { at: at(m) }) + } + _ => {} + } + // Poses that ended stop their keyframes. + let p = pose(m); + if p != Pose::Roaring { + m.anim.states[ROAR].stop(); + } + if p != Pose::Sniffing { + m.anim.states[SNIFF].stop(); + } + if p != Pose::Emerging { + m.anim.states[EMERGE].stop(); + } + if p != Pose::Digging { + m.anim.states[DIGGING].stop(); + } + if m.anim.states[ATTACK] + .millis(m.age as f32) + .is_some_and(|ms| ms > 1000) + { + m.anim.states[ATTACK].stop(); + } + if m.anim.states[SONIC_BOOM] + .millis(m.age as f32) + .is_some_and(|ms| ms > 3500) + { + m.anim.states[SONIC_BOOM].stop(); + } +} +/// `Warden.getHeartBeatDelay`. +pub fn heart_beat_delay(client_anger: i32) -> i32 { + let anger = client_anger as f32 / AngerLevel::Angry.minimum() as f32; + 40 - (anger.clamp(0.0, 1.0) * 30.0).floor() as i32 +} +/// `Warden.getAmbientSound`: none while roaring, digging or emerging. +pub fn ambient_sound(m: &Mob) -> Option<&'static str> { + if pose(m) == Pose::Roaring || digging_or_emerging(m) { + None + } else { + Some(anger_level(m).ambient_sound()) + } +} +/// `getTendrilAnimation` / `getHeartAnimation` at the partial tick. +pub fn tendril_animation(m: &Mob, partial: f32) -> f32 { + m.anim.lerp(TENDRIL, partial) / 10.0 +} +pub fn heart_animation(m: &Mob, partial: f32) -> f32 { + m.anim.lerp(HEART, partial) / 10.0 +} + +// ---- model ---- + +/// `WardenModel.setupAnim`. +pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap) { + p.xrot("head", s.x_rot.to_radians()); + p.yrot("head", s.y_rot.to_radians()); + // animateWalk + let speed_modifier = (3.0 * s.speed).min(0.5); + let adjusted = s.pos * 0.8662; + let (cos, sin) = (adjusted.cos(), adjusted.sin()); + let speed_min = speed_modifier.min(0.35); + let head_z = p.get("head")[5] + 0.3 * sin * speed_modifier; + p.zrot("head", head_z); + let head_x = p.get("head")[3] + 1.2 * (adjusted + PI / 2.0).cos() * speed_min; + p.xrot("head", head_x); + p.zrot("body", 0.1 * sin * speed_modifier); + p.xrot("body", cos * speed_min); + p.xrot("left_leg", cos * speed_modifier); + p.xrot("right_leg", (adjusted + PI).cos() * speed_modifier); + p.xrot("left_arm", -(0.8 * cos * speed_modifier)); + p.zrot("left_arm", 0.0); + p.xrot("right_arm", -(0.8 * sin * speed_modifier)); + p.zrot("right_arm", 0.0); + for (arm, x) in [("left_arm", 13.0), ("right_arm", -13.0)] { + let a = p.get(arm); + a[4] = 0.0; + a[2] = 1.0; + a[0] = x; + a[1] = -13.0; + } + // animateIdlePose + let scaled = s.age * 0.1; + let (wobble_cos, wobble_sin) = (scaled.cos(), scaled.sin()); + let head_z = p.get("head")[5] + 0.06 * wobble_cos; + p.zrot("head", head_z); + let head_x = p.get("head")[3] + 0.06 * wobble_sin; + p.xrot("head", head_x); + let body_z = p.get("body")[5] + 0.025 * wobble_sin; + p.zrot("body", body_z); + let body_x = p.get("body")[3] + 0.025 * wobble_cos; + p.xrot("body", body_x); + // animateTendrils + let tendril = tendril_animation(m, s.partial) + * ((f64::from(s.age) * 2.25).cos() * std::f64::consts::PI * f64::from(0.1f32)) as f32; + p.xrot("left_tendril", tendril); + p.xrot("right_tendril", -tendril); + for (slot, name) in [ + (ATTACK, "WARDEN_ATTACK"), + (SONIC_BOOM, "WARDEN_SONIC_BOOM"), + (DIGGING, "WARDEN_DIG"), + (EMERGE, "WARDEN_EMERGE"), + (ROAR, "WARDEN_ROAR"), + (SNIFF, "WARDEN_SNIFF"), + ] { + if let (Some(ms), Some(a)) = ( + m.anim.states[slot].millis(s.age), + animations.get(&format!("WardenAnimation.{name}")), + ) { + a.apply(ms, 1.0, p); + } + } +} +/// The emissive layers of `WardenRenderer`: the bioluminescent skin, the +/// pulsating spots, the tendrils and the heart, as (model, texture, alpha). +pub fn emissive_layers(m: &Mob, partial: f32) -> [(&'static str, &'static str, f32); 5] { + let age = m.age as f32 + partial; + [ + ( + "warden#bioluminescent", + "entity/warden/warden_bioluminescent_layer", + 1.0, + ), + ( + "warden#pulsating_spots", + "entity/warden/warden_pulsating_spots_1", + ((age * 0.045).cos() * 0.25).max(0.0), + ), + ( + "warden#pulsating_spots", + "entity/warden/warden_pulsating_spots_2", + ((age * 0.045 + PI).cos() * 0.25).max(0.0), + ), + ( + "warden#tendrils", + "entity/warden/warden", + tendril_animation(m, partial), + ), + ( + "warden#heart", + "entity/warden/warden_heart", + heart_animation(m, partial), + ), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn anger_levels_follow_the_thresholds() { + assert_eq!(AngerLevel::by_anger(0), AngerLevel::Calm); + assert_eq!(AngerLevel::by_anger(39), AngerLevel::Calm); + assert_eq!(AngerLevel::by_anger(40), AngerLevel::Agitated); + assert_eq!(AngerLevel::by_anger(79), AngerLevel::Agitated); + assert_eq!(AngerLevel::by_anger(80), AngerLevel::Angry); + assert!(AngerLevel::Angry.is_angry()); + assert_eq!(AngerLevel::Calm.ambient_sound(), "entity.warden.ambient"); + assert_eq!( + AngerLevel::Agitated.listening_sound(), + "entity.warden.listening_angry" + ); + } + + #[test] + fn anger_accumulates_to_a_cap_and_decays_each_second() { + let mut a = AngerManagement::default(); + assert_eq!(a.increase(Who::Player, 35), 35); + assert_eq!(a.increase(Who::Player, 35), 70); + assert_eq!(a.increase(Who::Player, 100), 150); + assert_eq!(a.active_anger(None), 150); + a.tick(|_| true); + assert_eq!(a.anger_of(Who::Player), 149); + // An invalid suspect is forgotten. + a.increase(Who::Mob(3), 10); + a.tick(|w| w == Who::Player); + assert_eq!(a.anger_of(Who::Mob(3)), 0); + assert_eq!(a.suspects(), &[Who::Player]); + // Anger of one point is gone after the next second. + let mut b = AngerManagement::default(); + b.increase(Who::Mob(1), 1); + b.tick(|_| true); + assert!(b.suspects().is_empty()); + } + + #[test] + fn the_angriest_player_comes_first() { + let mut a = AngerManagement::default(); + a.increase(Who::Mob(1), 90); + a.increase(Who::Player, 50); + a.increase(Who::Mob(2), 120); + // Angry suspects first, the angrier mob before the weaker one... + assert_eq!(a.suspects(), &[Who::Mob(2), Who::Mob(1), Who::Player]); + // ...until the player is angry as well: players lead ties of level. + a.increase(Who::Player, 40); + assert_eq!(a.suspects()[0], Who::Player); + assert_eq!(a.active_entity(|w| w != Who::Player), Some(Who::Mob(2))); + assert_eq!(a.active_anger(Some(Who::Mob(1))), 90); + assert_eq!(a.active_anger(Some(Who::Mob(9))), 0); + a.clear(Who::Player); + assert_eq!(a.suspects(), &[Who::Mob(2), Who::Mob(1)]); + assert_eq!(a.active_anger(None), 120); + } + + #[test] + fn a_single_suspect_sets_the_highest_anger() { + let mut a = AngerManagement::default(); + a.increase(Who::Mob(5), 44); + assert_eq!(a.active_anger(None), 44); + a.clear(Who::Mob(5)); + assert_eq!(a.active_anger(None), 0); + } + + #[test] + fn the_heart_beats_faster_when_angry() { + assert_eq!(heart_beat_delay(0), 40); + assert_eq!(heart_beat_delay(40), 25); + assert_eq!(heart_beat_delay(80), 10); + assert_eq!(heart_beat_delay(150), 10); + } + + #[test] + fn memories_expire_with_their_ttl() { + let mut st = Warden::default(); + // Set during the brain: present for exactly the ttl. + st.in_brain = true; + let until = st.expiry(100, 5); + assert!(present(until, 104)); + assert!(!present(until, 105)); + // Set before the brain's tick: that tick already counts. + st.in_brain = false; + let until = st.expiry(100, 5); + assert!(present(until, 103)); + assert!(!present(until, 104)); + } + + #[test] + fn the_pose_codes_round_trip() { + for p in [ + Pose::Standing, + Pose::Emerging, + Pose::Digging, + Pose::Roaring, + Pose::Sniffing, + ] { + assert_eq!(Pose::from_code(p.code()), p); + } + } +} diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 8fa53a860..2a02cd37a 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -119,6 +119,12 @@ particle_types! { Soul = "soul", SculkSoul = "sculk_soul", DragonBreath = "dragon_breath", + DustColorTransition = "dust_color_transition", + SculkCharge = "sculk_charge", + SculkChargePop = "sculk_charge_pop", + Shriek = "shriek", + SonicBoom = "sonic_boom", + Vibration = "vibration", } impl ParticleType { /// `ParticleType.getOverrideLimiter`: spawned regardless of distance. @@ -138,8 +144,11 @@ pub struct ParticleOptions { pub block: Option<(String, u32)>, /// RGB(A) for dust, spells, entity effects and tinted leaves. pub color: [f32; 4], - /// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`. + /// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`, + /// `SculkChargeParticleOptions.roll`, `ShriekParticleOption.delay`. pub scale: f32, + /// `DustColorTransitionOptions.toColor` (`color` is the from colour). + pub to_color: [f32; 3], } impl ParticleOptions { pub fn simple(ty: ParticleType) -> Self { @@ -148,6 +157,41 @@ impl ParticleOptions { block: None, color: [1.0; 4], scale: 1.0, + to_color: [1.0, 0.0, 0.0], + } + } + /// `DustColorTransitionOptions`. + pub fn dust_transition(from: [f32; 3], to: [f32; 3], scale: f32) -> Self { + Self { + color: [from[0], from[1], from[2], 1.0], + to_color: to, + scale: scale.clamp(0.01, 4.0), + ..Self::simple(ParticleType::DustColorTransition) + } + } + /// `DustColorTransitionOptions.SCULK_TO_REDSTONE`. + pub fn sculk_to_redstone() -> Self { + let rgb = |c: u32| { + [ + ((c >> 16) & 255) as f32 / 255.0, + ((c >> 8) & 255) as f32 / 255.0, + (c & 255) as f32 / 255.0, + ] + }; + Self::dust_transition(rgb(3_790_560), rgb(16_711_680), 1.0) + } + /// `SculkChargeParticleOptions(roll)`. + pub fn sculk_charge(roll: f32) -> Self { + Self { + scale: roll, + ..Self::simple(ParticleType::SculkCharge) + } + } + /// `ShriekParticleOption(delay)`. + pub fn shriek(delay: i32) -> Self { + Self { + scale: delay as f32, + ..Self::simple(ParticleType::Shriek) } } pub fn block(ty: ParticleType, sprite: String, tint: u32) -> Self { @@ -188,6 +232,8 @@ enum Size { Lava, Portal, ReversePortal, + /// `ShriekParticle.getQuadSize`. + Shriek, } #[derive(Clone, Copy, Debug, PartialEq)] enum Light { @@ -261,6 +307,23 @@ enum Behaviour { DragonBreath { hit_ground: bool, }, + /// `ShriekParticle`: waits `delay` ticks, then rises. + Shriek { + delay: i32, + }, + /// `VibrationSignalParticle`: flies to a listener. + Vibration { + dest: [f64; 3], + rot: f32, + rot_o: f32, + pitch: f32, + pitch_o: f32, + }, + /// `DustColorTransitionParticle`: from one colour to the other. + Transition { + from: [f32; 3], + to: [f32; 3], + }, } #[derive(Clone, Copy, Debug, PartialEq)] enum DripStage { @@ -511,6 +574,7 @@ impl Particle { Size::ReversePortal => { self.size * (1.0 - (self.age as f32 + a) / (self.lifetime as f32 * 1.5)) } + Size::Shriek => self.size * (t * 0.75).clamp(0.0, 1.0), } } } @@ -655,6 +719,27 @@ impl ParticleEngine { self.particles.clear(); self.pending.clear(); } + /// A vibration signal flying from `from` to `to` in `ticks` + /// (`VibrationParticleOption`). + pub fn vibration(&mut self, from: [f64; 3], to: [f64; 3], ticks: i32) { + let mut q = Particle::blank(ParticleType::Vibration, from); + q.size = 0.3; + q.lifetime = ticks; + q.has_physics = false; + q.light = Light::Block15; + q.set = self.set_of(ParticleType::Vibration); + let d = [from[0] - to[0], from[1] - to[1], from[2] - to[2]]; + let rot = d[0].atan2(d[2]) as f32; + let pitch = d[1].atan2((d[0] * d[0] + d[2] * d[2]).sqrt()) as f32; + q.behaviour = Behaviour::Vibration { + dest: to, + rot, + rot_o: rot, + pitch, + pitch_o: pitch, + }; + self.pending.push(q); + } /// `ParticleEngine.add` (via `particlesToAdd`, applied on the next tick). pub fn push(&mut self, particle: Particle) { self.pending.push(particle); @@ -1411,12 +1496,17 @@ impl ParticleEngine { q.set = set; q } - T::Explosion => { + T::Explosion | T::SonicBoom => { let mut q = Particle::moving(r, ty, p, [0.0; 3]); q.lifetime = 6 + r.next_int_bound(4).unwrap_or(0); let col = r.next_float() * 0.6 + 0.4; q.set_color(col, col, col); q.size = 2.0 * (1.0 - v[0] as f32 * 0.5); + if ty == T::SonicBoom { + // SonicBoomParticle. + q.lifetime = 16; + q.size = 1.5; + } q.light = Light::FullBright; q.behaviour = Behaviour::HugeExplosion; q.set = set; @@ -1470,6 +1560,69 @@ impl ParticleEngine { q.size_curve = Size::GrowIn; q } + T::DustColorTransition => { + let mut q = Particle::moving(r, ty, p, v); + q.friction = 0.96; + q.speed_up_when_y_blocked = true; + for c in &mut q.velocity { + *c *= f64::from(0.1f32); + } + q.size *= 0.75 * o.scale; + let base = (8.0 / (r.next_double() * 0.8 + 0.2)) as i32; + q.lifetime = ((base as f32 * o.scale).max(1.0)) as i32; + let factor = r.next_float() * 0.4 + 0.6; + let mut randomize = |c: f32| (r.next_float() * 0.2 + 0.8) * c * factor; + let from = [ + randomize(o.color[0]), + randomize(o.color[1]), + randomize(o.color[2]), + ]; + let to = [ + randomize(o.to_color[0]), + randomize(o.to_color[1]), + randomize(o.to_color[2]), + ]; + q.size_curve = Size::GrowIn; + q.behaviour = Behaviour::Transition { from, to }; + q.set = set; + q + } + // SculkChargeParticle / SculkChargePopParticle. + T::SculkCharge | T::SculkChargePop => { + let mut q = Particle::moving(r, ty, p, v); + q.friction = 0.96; + q.scale(if ty == T::SculkCharge { 1.5 } else { 1.0 }); + q.has_physics = false; + q.velocity = v; + q.light = Light::Block15; + q.behaviour = Behaviour::Animated; + q.set = set; + if ty == T::SculkCharge { + q.roll = o.scale; + q.o_roll = o.scale; + q.lifetime = r.next_int_bound(12).unwrap_or(0) + 8; + } else { + q.lifetime = r.next_int_bound(4).unwrap_or(0) + 6; + } + q + } + // Vibration signals are created by `vibration`, aimed at a listener. + T::Vibration => return None, + // ShriekParticle. + T::Shriek => { + let mut q = Particle::moving(r, ty, p, [0.0; 3]); + q.size = 0.85; + q.lifetime = 30; + q.gravity = 0.0; + q.velocity = [0.0, 0.1, 0.0]; + q.light = Light::Block15; + q.size_curve = Size::Shriek; + q.behaviour = Behaviour::Shriek { + delay: o.scale as i32, + }; + q.set = set; + q + } T::Dust => { let mut q = Particle::moving(r, ty, p, v); q.friction = 0.96; @@ -2146,6 +2299,49 @@ impl ParticleEngine { start[2] + p.velocity[2] * f64::from(pos), ]; } + Behaviour::Transition { .. } => { + p.base_tick(level); + self.sprite_from_age(p); + } + Behaviour::Shriek { delay } => { + if delay > 0 { + p.behaviour = Behaviour::Shriek { delay: delay - 1 }; + } else { + p.base_tick(level); + self.sprite_from_age(p); + } + } + Behaviour::Vibration { + dest, rot, pitch, .. + } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + let remaining = p.lifetime - p.age; + if remaining > 0 { + let alpha = 1.0 / f64::from(remaining); + for i in 0..3 { + p.position[i] += (dest[i] - p.position[i]) * alpha; + } + } + let d = [ + p.position[0] - dest[0], + p.position[1] - dest[1], + p.position[2] - dest[2], + ]; + p.behaviour = Behaviour::Vibration { + dest, + rot: d[0].atan2(d[2]) as f32, + rot_o: rot, + pitch: d[1].atan2((d[0] * d[0] + d[2] * d[2]).sqrt()) as f32, + pitch_o: pitch, + }; + self.sprite_from_age(p); + } Behaviour::HugeExplosion => { p.previous = p.position; let age = p.age; @@ -2403,6 +2599,58 @@ impl ParticleEngine { if let Behaviour::FlyTowards { alpha: la, .. } = p.behaviour { alpha = lifetime_alpha(la, p.age, p.lifetime, partial); } + let mut rotations = [Some(rotation), None]; + let mut rgb = [p.rgba[0], p.rgba[1], p.rgba[2]]; + match p.behaviour { + // ShriekParticle.extract: two tilted quads, fading out. + Behaviour::Shriek { delay } => { + if delay > 0 { + continue; + } + alpha = 1.0 - ((p.age as f32 + partial) / p.lifetime as f32).clamp(0.0, 1.0); + rotations = [ + Some(Quat::from_rotation_x(-1.0472)), + Some(Quat::from_euler( + glam::EulerRot::YXZ, + -std::f32::consts::PI, + 1.0472, + 0.0, + )), + ]; + } + // VibrationSignalParticle.extract: two quads along the flight. + Behaviour::Vibration { + rot, + rot_o, + pitch, + pitch_o, + .. + } => { + let sway = + ((p.age as f32 + partial - std::f32::consts::TAU) * 0.05).sin() * 2.0; + let lerped_rot = rot_o + (rot - rot_o) * partial; + let lerped_pitch = + pitch_o + (pitch - pitch_o) * partial + std::f32::consts::FRAC_PI_2; + rotations = [ + Some( + Quat::from_rotation_y(lerped_rot) + * Quat::from_rotation_x(-lerped_pitch) + * Quat::from_rotation_y(sway), + ), + Some( + Quat::from_rotation_y(-std::f32::consts::PI + lerped_rot) + * Quat::from_rotation_x(lerped_pitch) + * Quat::from_rotation_y(sway), + ), + ]; + } + // DustColorTransitionParticle.lerpColors. + Behaviour::Transition { from, to } => { + let t = (p.age as f32 + partial) / (p.lifetime as f32 + 1.0); + rgb = std::array::from_fn(|i| from[i] + (to[i] - from[i]) * t); + } + _ => {} + } let block = ParticleLevel::block_at(p.position); let packed = light_at(block); let (sky, mut block_light) = (u32::from(packed >> 4) * 16, u32::from(packed & 15) * 16); @@ -2424,7 +2672,7 @@ impl ParticleEngine { } let light = sky_light | block_light << 8; let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0) as u32; - let color = c(alpha) << 24 | c(p.rgba[2]) << 16 | c(p.rgba[1]) << 8 | c(p.rgba[0]); + let color = c(alpha) << 24 | c(rgb[2]) << 16 | c(rgb[1]) << 8 | c(rgb[0]); let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0); let (u0, v0, u1, v1) = ( r.u0 + du * p.uv[0], @@ -2432,20 +2680,22 @@ impl ParticleEngine { r.u0 + du * p.uv[2], r.v0 + dv * p.uv[3], ); - for (n, uv) in [ - ((1.0, -1.0), [u1, v1]), - ((1.0, 1.0), [u1, v0]), - ((-1.0, 1.0), [u0, v0]), - ((-1.0, -1.0), [u0, v1]), - ] { - let v = center + rotation * FVec3::new(n.0, n.1, 0.0) * size; - out.push(Vertex { - pos: v.to_array(), - uv, - layer: 0, - color, - light, - }); + for rotation in rotations.into_iter().flatten() { + for (n, uv) in [ + ((1.0, -1.0), [u1, v1]), + ((1.0, 1.0), [u1, v0]), + ((-1.0, 1.0), [u0, v0]), + ((-1.0, -1.0), [u0, v1]), + ] { + let v = center + rotation * FVec3::new(n.0, n.1, 0.0) * size; + out.push(Vertex { + pos: v.to_array(), + uv, + layer: 0, + color, + light, + }); + } } } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index bcca25e8a..326269b8e 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -400,6 +400,7 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b entries.push(("Page", Tag::Int(l.page))); } } + BlockEntity::Sculk(s) => entries.extend(s.to_nbt()), } Tag::compound(entries) } @@ -474,6 +475,7 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; } BlockEntity::Sign(sign) => sign.decode(tag), + BlockEntity::Sculk(s) => s.load(tag), BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) => {} } Some((pos, entity)) diff --git a/crates/horizon-client/src/sculk.rs b/crates/horizon-client/src/sculk.rs new file mode 100644 index 000000000..64d61fefb --- /dev/null +++ b/crates/horizon-client/src/sculk.rs @@ -0,0 +1,885 @@ +//! Game events and the vibration system (`GameEvent`, `VibrationSystem`, +//! `VibrationSelector`) shared by sculk sensors, shriekers and wardens, the +//! sculk block entities and the per-player warden spawn tracker. +use crate::mobs::Who; +use horizon_core::{ + geometry::{Direction, Vec3, traverse_blocks}, + position::BlockPos, +}; +use horizon_world::{level::sculk::SculkSpreader, nbt::Tag}; + +/// Every `GameEvent` with its `VibrationSystem` frequency (0: none). +const EVENTS: &[(&str, i32)] = &[ + ("minecraft:step", 1), + ("minecraft:swim", 1), + ("minecraft:flap", 1), + ("minecraft:projectile_land", 2), + ("minecraft:hit_ground", 2), + ("minecraft:splash", 2), + ("minecraft:bounce", 2), + ("minecraft:item_interact_finish", 3), + ("minecraft:projectile_shoot", 3), + ("minecraft:instrument_play", 3), + ("minecraft:entity_action", 4), + ("minecraft:elytra_glide", 4), + ("minecraft:unequip", 4), + ("minecraft:entity_dismount", 5), + ("minecraft:equip", 5), + ("minecraft:entity_interact", 6), + ("minecraft:shear", 6), + ("minecraft:entity_mount", 6), + ("minecraft:entity_damage", 7), + ("minecraft:drink", 8), + ("minecraft:eat", 8), + ("minecraft:container_close", 9), + ("minecraft:block_close", 9), + ("minecraft:block_deactivate", 9), + ("minecraft:block_detach", 9), + ("minecraft:container_open", 10), + ("minecraft:block_open", 10), + ("minecraft:block_activate", 10), + ("minecraft:block_attach", 10), + ("minecraft:prime_fuse", 10), + ("minecraft:note_block_play", 10), + ("minecraft:block_change", 11), + ("minecraft:block_destroy", 12), + ("minecraft:fluid_pickup", 12), + ("minecraft:block_place", 13), + ("minecraft:fluid_place", 13), + ("minecraft:entity_place", 14), + ("minecraft:lightning_strike", 14), + ("minecraft:teleport", 14), + ("minecraft:entity_die", 15), + ("minecraft:explode", 15), + // Events that exist but make no vibration frequency. + ("minecraft:item_interact_start", 0), + ("minecraft:jukebox_play", 0), + ("minecraft:jukebox_stop_play", 0), + ("minecraft:sculk_sensor_tendrils_clicking", 0), + ("minecraft:shriek", 0), +]; +/// `GameEvent.RESONATE_1..15`. +pub const RESONANCE: [&str; 15] = [ + "minecraft:resonate_1", + "minecraft:resonate_2", + "minecraft:resonate_3", + "minecraft:resonate_4", + "minecraft:resonate_5", + "minecraft:resonate_6", + "minecraft:resonate_7", + "minecraft:resonate_8", + "minecraft:resonate_9", + "minecraft:resonate_10", + "minecraft:resonate_11", + "minecraft:resonate_12", + "minecraft:resonate_13", + "minecraft:resonate_14", + "minecraft:resonate_15", +]; +pub const SHRIEK: &str = "minecraft:shriek"; +pub const TENDRILS_CLICKING: &str = "minecraft:sculk_sensor_tendrils_clicking"; +pub const NO_VIBRATION_FREQUENCY: i32 = 0; + +/// `VibrationSystem.getGameEventFrequency`. +pub fn frequency(event: &str) -> i32 { + if let Some(i) = RESONANCE.iter().position(|e| *e == event) { + return i as i32 + 1; + } + EVENTS + .iter() + .find(|(name, _)| *name == event) + .map_or(0, |(_, f)| *f) +} +/// `GameEvent.notificationRadius`. +pub fn notification_radius(event: &str) -> i32 { + match event { + "minecraft:jukebox_play" | "minecraft:jukebox_stop_play" => 10, + SHRIEK => 32, + _ => 16, + } +} +/// The identifier as a `'static` string, for loading saved events. +pub fn intern(event: &str) -> Option<&'static str> { + RESONANCE + .iter() + .chain(EVENTS.iter().map(|(name, _)| name)) + .find(|e| **e == event) + .copied() +} +/// `GameEventTags.VIBRATIONS`: every event with a frequency, resonance and flap. +pub fn is_vibration(event: &str) -> bool { + frequency(event) != 0 +} +/// `GameEventTags.SHRIEKER_CAN_LISTEN`. +pub fn shrieker_can_listen(event: &str) -> bool { + event == TENDRILS_CLICKING +} +/// `GameEventTags.WARDEN_CAN_LISTEN`: vibrations except flap, plus shrieks and +/// tendril clicks. +pub fn warden_can_listen(event: &str) -> bool { + (is_vibration(event) && event != "minecraft:flap") + || event == SHRIEK + || shrieker_can_listen(event) +} +/// `GameEventTags.IGNORE_VIBRATIONS_SNEAKING`. +pub fn ignored_when_sneaking(event: &str) -> bool { + matches!( + event, + "minecraft:hit_ground" + | "minecraft:projectile_shoot" + | "minecraft:step" + | "minecraft:swim" + | "minecraft:item_interact_start" + | "minecraft:item_interact_finish" + ) +} +/// `VibrationSystem.getRedstoneStrengthForDistance`. +pub fn redstone_strength(distance: f32, listener_radius: i32) -> i32 { + let scale = 15.0 / f64::from(listener_radius); + (15 - (scale * f64::from(distance)).floor() as i32).max(1) +} +/// `SculkSensorBlock.RESONANCE_PITCH_BEND`: `NoteBlock.getPitchFromNote`. +pub fn resonance_pitch(frequency: i32) -> f32 { + const TONES: [i32; 16] = [0, 0, 2, 4, 6, 7, 9, 10, 12, 14, 15, 18, 19, 21, 22, 24]; + 2.0f32.powf((TONES[frequency.clamp(0, 15) as usize] - 12) as f32 / 12.0) +} + +/// What an event's source looks like to listeners, captured when it is +/// posted (`GameEvent.Context` plus the entity facts listeners ask for). +#[derive(Clone, Copy, Debug, Default)] +pub struct Context { + pub source: Option, + /// The projectile's owner, when the source is a projectile. + pub owner: Option, + /// `affectedState` is in `dampens_vibrations`. + pub dampening_state: bool, + /// The source is a spectator. + pub spectator: bool, + /// `isSteppingCarefully` (sneaking). + pub stepping_carefully: bool, + /// `dampensVibrations` (a warden). + pub dampens: bool, + /// The source is a living entity wardens may target. + pub targetable: bool, + /// The source is a living entity at all. + pub living: bool, + /// The source is the player, rides with them, or is their projectile + /// (`SculkShriekerBlockEntity.tryGetPlayer`). + pub player: bool, +} +/// `VibrationSystem.User.isValidVibration` without the tag test. +pub fn valid_vibration(listens: bool, event: &str, ctx: &Context) -> bool { + if !listens { + return false; + } + if ctx.source.is_some() { + if ctx.spectator { + return false; + } + if ctx.stepping_carefully && ignored_when_sneaking(event) { + return false; + } + if ctx.dampens { + return false; + } + } + !ctx.dampening_state +} + +/// `VibrationInfo`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Info { + pub event: &'static str, + pub distance: f32, + pub pos: [f64; 3], + pub source: Option, + pub owner: Option, +} +/// `VibrationSelector`: the closest, then highest-frequency candidate of a tick. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Selector { + current: Option<(Info, i64)>, +} +impl Selector { + pub fn add_candidate(&mut self, new: Info, tick: i64) { + if self.should_replace(&new, tick) { + self.current = Some((new, tick)); + } + } + fn should_replace(&self, new: &Info, tick: i64) -> bool { + let Some((previous, previous_tick)) = &self.current else { + return true; + }; + if tick != *previous_tick { + return false; + } + if new.distance < previous.distance { + true + } else if new.distance > previous.distance { + false + } else { + frequency(new.event) > frequency(previous.event) + } + } + pub fn chosen_candidate(&self, time: i64) -> Option { + self.current + .filter(|(_, tick)| *tick < time) + .map(|(info, _)| info) + } + pub fn start_over(&mut self) { + self.current = None; + } +} +/// `VibrationSystem.Data`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Data { + pub current: Option, + pub travel: i32, + pub selector: Selector, +} +/// What one `VibrationSystem.Ticker.tick` did. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Tick { + /// A vibration was chosen: its travel time (the particle starts). + pub started: Option<(Info, i32)>, + /// A vibration arrived. + pub received: Option, + /// `onDataChanged`. + pub changed: bool, +} +impl Data { + /// `Listener.handleGameEvent` once the user accepted the event. + pub fn schedule(&mut self, info: Info, game_time: i64) { + self.selector.add_candidate(info, game_time); + } + /// `VibrationSystem.Ticker.tick`. + pub fn tick( + &mut self, + game_time: i64, + chunks_ticking: bool, + needs_ticking_chunks: bool, + travel_time: impl Fn(f32) -> i32, + ) -> Tick { + let mut out = Tick::default(); + if self.current.is_none() + && let Some(info) = self.selector.chosen_candidate(game_time) + { + self.current = Some(info); + self.travel = travel_time(info.distance); + out.started = Some((info, self.travel)); + out.changed = true; + self.selector.start_over(); + } + if let Some(info) = self.current { + let mut changed = self.travel > 0; + self.travel = (self.travel - 1).max(0); + if self.travel <= 0 { + if needs_ticking_chunks && !chunks_ticking { + changed = false; + } else { + out.received = Some(info); + self.current = None; + changed = true; + } + } + out.changed |= changed; + } + out + } + /// The `listener` compound (`VibrationSystem.Data.CODEC`). + pub fn to_nbt(&self) -> Tag { + let mut entries: Vec<(&str, Tag)> = Vec::new(); + if let Some(info) = &self.current { + entries.push(("event", info_to_nbt(info))); + } + let mut selector: Vec<(&str, Tag)> = Vec::new(); + let chosen = self.selector.current; + if let Some((info, _)) = &chosen { + selector.push(("event", info_to_nbt(info))); + } + selector.push(("tick", Tag::Long(chosen.map_or(-1, |(_, t)| t)))); + entries.push(("selector", Tag::compound(selector))); + entries.push(("event_delay", Tag::Int(self.travel))); + Tag::compound(entries) + } + pub fn from_nbt(tag: &Tag) -> Self { + let mut data = Self::default(); + data.current = tag.get("event").and_then(info_from_nbt); + if let Some(Tag::Int(t)) = tag.get("event_delay") { + data.travel = (*t).max(0); + } + if let Some(selector) = tag.get("selector") { + let info = selector.get("event").and_then(info_from_nbt); + let tick = match selector.get("tick") { + Some(Tag::Long(t)) => *t, + _ => -1, + }; + data.selector.current = info.map(|i| (i, tick)); + } + data + } +} +fn info_to_nbt(info: &Info) -> Tag { + Tag::compound(vec![ + ("game_event", Tag::String(info.event.into())), + ("distance", Tag::Float(info.distance.to_bits())), + ( + "pos", + Tag::List(info.pos.iter().map(|v| Tag::Double(v.to_bits())).collect()), + ), + ]) +} +fn info_from_nbt(tag: &Tag) -> Option { + let event = intern(&crate::save::text(tag.get("game_event"))?)?; + let distance = match tag.get("distance") { + Some(Tag::Float(f)) => f32::from_bits(*f), + _ => 0.0, + }; + let pos = match tag.get("pos") { + Some(Tag::List(v)) if v.len() == 3 => { + let mut p = [0.0; 3]; + for (i, t) in v.iter().enumerate() { + if let Tag::Double(d) = t { + p[i] = f64::from_bits(*d); + } + } + p + } + _ => return None, + }; + Some(Info { + event, + distance, + pos, + source: None, + owner: None, + }) +} + +/// `Listener.isOccluded`: whether wool-like blocks block every line between +/// the centres of the source and listener blocks (nudged one direction each). +pub fn is_occluded( + origin: [f64; 3], + dest: [f64; 3], + mut occludes: impl FnMut(BlockPos) -> bool, +) -> bool { + let centre = + |p: [f64; 3]| Vec3::new(p[0].floor() + 0.5, p[1].floor() + 0.5, p[2].floor() + 0.5); + let from = centre(origin); + let to = centre(dest); + for direction in Direction::ALL { + let nudged = from.relative(direction, f64::from(1.0e-5f32)); + let hit = traverse_blocks(nudged, to, 512, |p| occludes(p).then_some(())); + if !matches!(hit, Ok(Some(()))) { + return false; + } + } + true +} + +/// Which sculk block entity this is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SculkKind { + Sensor, + Calibrated, + Shrieker, + Catalyst, +} +/// `SculkSensorBlockEntity`, `CalibratedSculkSensorBlockEntity`, +/// `SculkShriekerBlockEntity` and `SculkCatalystBlockEntity`. +#[derive(Clone, Debug)] +pub struct SculkEntity { + pub kind: SculkKind, + pub vibration: Data, + /// `last_vibration_frequency` (sensors). + pub last_frequency: i32, + /// `warning_level` (shriekers). + pub warning_level: i32, + /// The catalyst's charge cursors. + pub spreader: SculkSpreader, +} +impl SculkEntity { + pub fn new(kind: SculkKind) -> Self { + Self { + kind, + vibration: Data::default(), + last_frequency: 0, + warning_level: 0, + spreader: SculkSpreader::default(), + } + } + pub fn for_block(name: &str) -> Option { + Some(Self::new(match name { + "minecraft:sculk_sensor" => SculkKind::Sensor, + "minecraft:calibrated_sculk_sensor" => SculkKind::Calibrated, + "minecraft:sculk_shrieker" => SculkKind::Shrieker, + "minecraft:sculk_catalyst" => SculkKind::Catalyst, + _ => return None, + })) + } + pub fn id(&self) -> &'static str { + match self.kind { + SculkKind::Sensor => "minecraft:sculk_sensor", + SculkKind::Calibrated => "minecraft:calibrated_sculk_sensor", + SculkKind::Shrieker => "minecraft:sculk_shrieker", + SculkKind::Catalyst => "minecraft:sculk_catalyst", + } + } + /// `VibrationSystem.User.getListenerRadius`. + pub fn listener_radius(&self) -> i32 { + match self.kind { + SculkKind::Calibrated => 16, + SculkKind::Sensor | SculkKind::Shrieker | SculkKind::Catalyst => 8, + } + } + /// The block entity's saved fields. + pub fn to_nbt(&self) -> Vec<(&'static str, Tag)> { + match self.kind { + SculkKind::Sensor | SculkKind::Calibrated => vec![ + ("last_vibration_frequency", Tag::Int(self.last_frequency)), + ("listener", self.vibration.to_nbt()), + ], + SculkKind::Shrieker => vec![ + ("warning_level", Tag::Int(self.warning_level)), + ("listener", self.vibration.to_nbt()), + ], + SculkKind::Catalyst => vec![("cursors", cursors_to_nbt(&self.spreader))], + } + } + pub fn load(&mut self, tag: &Tag) { + match self.kind { + SculkKind::Sensor | SculkKind::Calibrated => { + if let Some(Tag::Int(f)) = tag.get("last_vibration_frequency") { + self.last_frequency = *f; + } + if let Some(l) = tag.get("listener") { + self.vibration = Data::from_nbt(l); + } + } + SculkKind::Shrieker => { + if let Some(Tag::Int(w)) = tag.get("warning_level") { + self.warning_level = *w; + } + if let Some(l) = tag.get("listener") { + self.vibration = Data::from_nbt(l); + } + } + SculkKind::Catalyst => { + if let Some(c) = tag.get("cursors") { + self.spreader = cursors_from_nbt(c); + } + } + } + } +} +fn cursors_to_nbt(spreader: &SculkSpreader) -> Tag { + Tag::List( + spreader + .cursors + .iter() + .map(|c| { + let mut e: Vec<(&str, Tag)> = vec![ + ("pos", Tag::IntArray(vec![c.pos.x, c.pos.y, c.pos.z])), + ("charge", Tag::Int(c.charge)), + ("decay_delay", Tag::Int(c.decay_delay)), + ("update_delay", Tag::Int(c.update_delay)), + ]; + if let Some(faces) = &c.facings { + e.push(( + "facings", + Tag::List( + faces + .iter() + .map(|d| Tag::String(direction_name(*d).into())) + .collect(), + ), + )); + } + Tag::compound(e) + }) + .collect(), + ) +} +fn cursors_from_nbt(tag: &Tag) -> SculkSpreader { + use horizon_world::level::sculk::ChargeCursor; + let mut spreader = SculkSpreader::default(); + let Tag::List(items) = tag else { + return spreader; + }; + for item in items.iter().take(32) { + let Some(Tag::IntArray(p)) = item.get("pos") else { + continue; + }; + if p.len() != 3 { + continue; + } + let int = |k: &str, default: i32| match item.get(k) { + Some(Tag::Int(v)) => *v, + _ => default, + }; + let facings = match item.get("facings") { + Some(Tag::List(v)) => Some( + v.iter() + .filter_map(|t| match t { + Tag::String(s) => direction_from_name(&String::from_utf16_lossy(&s.0)), + _ => None, + }) + .collect(), + ), + _ => None, + }; + spreader.add_cursor(ChargeCursor { + pos: BlockPos::new(p[0], p[1], p[2]), + charge: int("charge", 0).clamp(0, 1000), + update_delay: int("update_delay", 0).max(0), + decay_delay: int("decay_delay", 1).clamp(0, 1), + facings, + }); + } + spreader +} +fn direction_name(d: Direction) -> &'static str { + match d { + Direction::Down => "down", + Direction::Up => "up", + Direction::North => "north", + Direction::South => "south", + Direction::West => "west", + Direction::East => "east", + } +} +fn direction_from_name(s: &str) -> Option { + Direction::ALL.into_iter().find(|d| direction_name(*d) == s) +} + +/// `WardenSpawnTracker`: a player's warning level toward summoning a warden. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct WardenSpawnTracker { + pub ticks_since_last_warning: i32, + pub warning_level: i32, + pub cooldown_ticks: i32, +} +impl WardenSpawnTracker { + pub const MAX_WARNING_LEVEL: i32 = 4; + /// Blocks around a shrieker within which players are warned. + pub const PLAYER_SEARCH_RADIUS: f64 = 16.0; + /// `AABB.ofSize(centre, 48, 48, 48)` for an existing warden. + pub const WARNING_CHECK_DIAMETER: f64 = 48.0; + const DECREASE_EVERY: i32 = 12000; + const INCREASE_COOLDOWN: i32 = 200; + pub fn tick(&mut self) { + if self.ticks_since_last_warning >= Self::DECREASE_EVERY { + self.set_warning_level(self.warning_level - 1); + self.ticks_since_last_warning = 0; + } else { + self.ticks_since_last_warning += 1; + } + if self.cooldown_ticks > 0 { + self.cooldown_ticks -= 1; + } + } + pub fn reset(&mut self) { + *self = Self::default(); + } + pub fn on_cooldown(&self) -> bool { + self.cooldown_ticks > 0 + } + /// `increaseWarningLevel`. + pub fn increase_warning_level(&mut self) { + if !self.on_cooldown() { + self.ticks_since_last_warning = 0; + self.cooldown_ticks = Self::INCREASE_COOLDOWN; + self.set_warning_level(self.warning_level + 1); + } + } + pub fn set_warning_level(&mut self, level: i32) { + self.warning_level = level.clamp(0, Self::MAX_WARNING_LEVEL); + } + /// `WardenSpawnTracker.tryWarn` over the trackers of the players around a + /// shrieker (the triggering player included): the new warning level, or + /// None when a warden is near or a player is cooling down. Every tracker + /// takes over the highest one. + pub fn try_warn(trackers: &mut [WardenSpawnTracker], warden_nearby: bool) -> Option { + if warden_nearby || trackers.iter().any(|t| t.on_cooldown()) { + return None; + } + // Stream.max keeps the last of equal maxima. + let index = trackers + .iter() + .enumerate() + .max_by_key(|(i, t)| (t.warning_level, *i)) + .map(|(i, _)| i)?; + trackers[index].increase_warning_level(); + let copy = trackers[index]; + for t in trackers.iter_mut() { + *t = copy; + } + Some(copy.warning_level) + } + pub fn to_nbt(&self) -> Tag { + Tag::compound(vec![ + ( + "ticks_since_last_warning", + Tag::Int(self.ticks_since_last_warning), + ), + ("warning_level", Tag::Int(self.warning_level)), + ("cooldown_ticks", Tag::Int(self.cooldown_ticks)), + ]) + } + pub fn from_nbt(tag: &Tag) -> Self { + let int = |k: &str| match tag.get(k) { + Some(Tag::Int(v)) => (*v).max(0), + _ => 0, + }; + Self { + ticks_since_last_warning: int("ticks_since_last_warning"), + warning_level: int("warning_level").min(Self::MAX_WARNING_LEVEL), + cooldown_ticks: int("cooldown_ticks"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn info(event: &'static str, distance: f32) -> Info { + Info { + event, + distance, + pos: [0.0; 3], + source: None, + owner: None, + } + } + + #[test] + fn frequencies_match_the_vanilla_table() { + assert_eq!(frequency("minecraft:step"), 1); + assert_eq!(frequency("minecraft:hit_ground"), 2); + assert_eq!(frequency("minecraft:projectile_shoot"), 3); + assert_eq!(frequency("minecraft:entity_damage"), 7); + assert_eq!(frequency("minecraft:eat"), 8); + assert_eq!(frequency("minecraft:block_open"), 10); + assert_eq!(frequency("minecraft:block_change"), 11); + assert_eq!(frequency("minecraft:block_place"), 13); + assert_eq!(frequency("minecraft:explode"), 15); + assert_eq!(frequency("minecraft:resonate_9"), 9); + assert_eq!(frequency("minecraft:shriek"), 0); + assert_eq!(frequency(TENDRILS_CLICKING), 0); + assert_eq!(frequency("minecraft:jukebox_play"), 0); + assert_eq!(frequency("minecraft:made_up"), 0); + } + + #[test] + fn event_tables_cover_resonance() { + for (i, name) in RESONANCE.iter().enumerate() { + assert_eq!(frequency(name), i as i32 + 1, "{name}"); + assert!(is_vibration(name)); + assert!(warden_can_listen(name)); + } + assert!(warden_can_listen(SHRIEK)); + assert!(warden_can_listen(TENDRILS_CLICKING)); + assert!(!warden_can_listen("minecraft:flap")); + assert!(is_vibration("minecraft:flap")); + assert!(shrieker_can_listen(TENDRILS_CLICKING)); + assert!(!shrieker_can_listen("minecraft:step")); + assert_eq!(notification_radius(SHRIEK), 32); + assert_eq!(notification_radius("minecraft:jukebox_play"), 10); + assert_eq!(notification_radius("minecraft:step"), 16); + } + + #[test] + fn redstone_strength_falls_with_distance() { + assert_eq!(redstone_strength(0.0, 8), 15); + assert_eq!(redstone_strength(1.0, 8), 14); + assert_eq!(redstone_strength(4.0, 8), 8); + assert_eq!(redstone_strength(8.0, 8), 1); + assert_eq!(redstone_strength(8.0, 16), 8); + assert_eq!(redstone_strength(16.0, 16), 1); + } + + #[test] + fn selector_prefers_the_nearest_then_the_loudest() { + let mut s = Selector::default(); + s.add_candidate(info("minecraft:step", 5.0), 10); + s.add_candidate(info("minecraft:eat", 6.0), 10); + assert_eq!(s.chosen_candidate(11).unwrap().event, "minecraft:step"); + s.add_candidate(info("minecraft:block_place", 5.0), 10); + assert_eq!( + s.chosen_candidate(11).unwrap().event, + "minecraft:block_place" + ); + s.add_candidate(info("minecraft:eat", 2.0), 10); + assert_eq!(s.chosen_candidate(11).unwrap().event, "minecraft:eat"); + // A later tick never replaces the pending candidate. + s.add_candidate(info("minecraft:explode", 0.0), 11); + assert_eq!(s.chosen_candidate(11).unwrap().event, "minecraft:eat"); + // It is chosen only on a later tick than it was posted. + assert!(s.chosen_candidate(10).is_none()); + s.start_over(); + assert!(s.chosen_candidate(12).is_none()); + } + + #[test] + fn vibrations_travel_one_block_per_tick() { + let mut d = Data::default(); + d.schedule(info("minecraft:step", 3.2), 100); + let travel = |distance: f32| distance.floor() as i32; + // Posted this tick: nothing yet. + let t = d.tick(100, true, true, travel); + assert_eq!(t, Tick::default()); + // Chosen next tick with a travel time of three. + let t = d.tick(101, true, true, travel); + assert_eq!(t.started.map(|(_, n)| n), Some(3)); + assert!(t.received.is_none()); + assert!(d.tick(102, true, true, travel).received.is_none()); + let t = d.tick(103, true, true, travel); + assert_eq!(t.received.map(|i| i.event), Some("minecraft:step")); + assert!(d.current.is_none()); + } + + #[test] + fn nearby_vibrations_arrive_at_once() { + let mut d = Data::default(); + d.schedule(info("minecraft:eat", 0.4), 5); + let t = d.tick(6, true, true, |x| x.floor() as i32); + assert!(t.started.is_some()); + assert!(t.received.is_some()); + } + + #[test] + fn unloaded_neighbours_hold_a_vibration_back() { + let mut d = Data::default(); + d.schedule(info("minecraft:eat", 0.0), 5); + let t = d.tick(6, false, true, |_| 0); + assert!(t.started.is_some()); + assert!(t.received.is_none()); + assert!(d.current.is_some()); + let t = d.tick(7, true, true, |_| 0); + assert!(t.received.is_some()); + // Entities do not need the neighbours. + d.schedule(info("minecraft:eat", 0.0), 8); + assert!(d.tick(9, false, false, |_| 0).received.is_some()); + } + + #[test] + fn vibration_data_round_trips_through_nbt() { + let mut d = Data::default(); + d.schedule(info("minecraft:block_destroy", 4.0), 40); + d.tick(41, true, true, |x| x as i32); + d.schedule(info("minecraft:step", 2.0), 41); + let back = Data::from_nbt(&d.to_nbt()); + assert_eq!(back.travel, d.travel); + assert_eq!(back.current.map(|i| i.event), d.current.map(|i| i.event)); + assert_eq!(back.selector.current.map(|(_, t)| t), Some(41)); + } + + #[test] + fn wool_on_the_line_occludes() { + let origin = [0.5, 0.5, 0.5]; + let dest = [4.5, 0.5, 0.5]; + // A full wall of wool between them blocks all six nudged lines. + let wall = |p: BlockPos| p.x == 2; + assert!(is_occluded(origin, dest, wall)); + // One wool block on the line blocks the nudged lines too. + let single = |p: BlockPos| p == BlockPos::new(2, 0, 0); + assert!(is_occluded(origin, dest, single)); + // Wool off to the side lets the vibration through. + let aside = |p: BlockPos| p == BlockPos::new(2, 1, 0); + assert!(!is_occluded(origin, dest, aside)); + assert!(!is_occluded(origin, dest, |_| false)); + } + + #[test] + fn sneaking_ignores_footsteps_but_not_damage() { + let sneaking = Context { + source: Some(Who::Player), + stepping_carefully: true, + ..Context::default() + }; + assert!(!valid_vibration(true, "minecraft:step", &sneaking)); + assert!(!valid_vibration(true, "minecraft:hit_ground", &sneaking)); + assert!(valid_vibration(true, "minecraft:entity_damage", &sneaking)); + let wardenish = Context { + source: Some(Who::Mob(1)), + dampens: true, + ..Context::default() + }; + assert!(!valid_vibration( + true, + "minecraft:entity_damage", + &wardenish + )); + let on_wool = Context { + dampening_state: true, + ..Context::default() + }; + assert!(!valid_vibration(true, "minecraft:block_place", &on_wool)); + assert!(!valid_vibration( + false, + "minecraft:step", + &Context::default() + )); + } + + #[test] + fn resonance_pitch_follows_the_tone_map() { + assert!((resonance_pitch(0) - 0.5).abs() < 1e-6); + assert!((resonance_pitch(4) - 2.0f32.powf(-6.0 / 12.0)).abs() < 1e-6); + assert!((resonance_pitch(15) - 2.0).abs() < 1e-6); + } + + #[test] + fn warning_levels_rise_with_a_cooldown_and_decay() { + let mut t = WardenSpawnTracker::default(); + t.increase_warning_level(); + assert_eq!(t.warning_level, 1); + assert_eq!(t.cooldown_ticks, 200); + // Cooling down: no increase. + t.increase_warning_level(); + assert_eq!(t.warning_level, 1); + for _ in 0..200 { + t.tick(); + } + t.increase_warning_level(); + assert_eq!(t.warning_level, 2); + t.set_warning_level(9); + assert_eq!(t.warning_level, 4); + t.cooldown_ticks = 0; + t.ticks_since_last_warning = 12000; + t.tick(); + assert_eq!(t.warning_level, 3); + assert_eq!(t.ticks_since_last_warning, 0); + } + + #[test] + fn nearby_players_share_the_highest_warning() { + let mut trackers = [ + WardenSpawnTracker::default(), + WardenSpawnTracker { + warning_level: 2, + ..Default::default() + }, + ]; + assert_eq!(WardenSpawnTracker::try_warn(&mut trackers, true), None); + assert_eq!(WardenSpawnTracker::try_warn(&mut trackers, false), Some(3)); + assert_eq!(trackers[0], trackers[1]); + assert_eq!(trackers[0].cooldown_ticks, 200); + // Everyone is cooling down now. + assert_eq!(WardenSpawnTracker::try_warn(&mut trackers, false), None); + } + + #[test] + fn cursors_round_trip() { + let mut e = SculkEntity::new(SculkKind::Catalyst); + e.spreader.add_cursors(BlockPos::new(3, 4, 5), 1500); + e.spreader.cursors[1].facings = Some(vec![Direction::Up, Direction::East]); + let tag = Tag::compound(e.to_nbt()); + let mut back = SculkEntity::new(SculkKind::Catalyst); + back.load(&tag); + assert_eq!(back.spreader, e.spreader); + assert_eq!(back.spreader.cursors[0].charge, 1000); + assert_eq!(back.spreader.cursors[1].charge, 500); + } +} diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 657f4635f..c3c1ae6eb 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -26,6 +26,11 @@ pub struct World { /// Chunks changed since the last save. pub modified: HashSet<(i32, i32)>, pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>, + /// States (by id) whose writes are recorded in `watched_writes` (sculk + /// blocks, which need a block entity). + pub watched: Vec, + /// Writes of watched states: position, previous and new state. + pub watched_writes: Vec<((i32, i32, i32), u16, u16)>, /// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent /// within spawning range (local difficulty). pub inhabited: HashMap<(i32, i32), i64>, @@ -106,6 +111,8 @@ impl World { loaded_entities: Vec::new(), modified: HashSet::new(), block_entities: HashMap::new(), + watched: Vec::new(), + watched_writes: Vec::new(), inhabited: HashMap::new(), game_time: 0, day_time: 1000, @@ -177,6 +184,11 @@ impl World { } let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0 as u16); if u32::from(previous) != state.0 { + let watches = |id: u16| self.watched.get(usize::from(id)).copied().unwrap_or(false); + if watches(previous) || watches(state.0 as u16) { + self.watched_writes + .push(((x, y, z), previous, state.0 as u16)); + } self.revision = self.revision.wrapping_add(1); self.modified.insert((x >> 4, z >> 4)); let sy = (y - MIN_Y) >> 4; diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index b8fc50f60..9cc98c95a 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -250,8 +250,13 @@ pub enum LevelEvent { state: BlockStateId, effect: PlayerEffect, }, - /// `Level.gameEvent` (vibration system), by vanilla identifier. - GameEvent { pos: BlockPos, event: &'static str }, + /// `Level.gameEvent` (vibration system), by vanilla identifier, with the + /// affected block state when the event carries one. + GameEvent { + pos: BlockPos, + event: &'static str, + state: Option, + }, } /// The world as seen by block behaviour. Implemented by the game and tests. diff --git a/crates/horizon-world/src/level/place.rs b/crates/horizon-world/src/level/place.rs index 01e9527c2..09d14dfc0 100644 --- a/crates/horizon-world/src/level/place.rs +++ b/crates/horizon-world/src/level/place.rs @@ -1514,7 +1514,7 @@ impl Sim<'_, L> { volume: (sounds.volume + 1.0) / 2.0, pitch: sounds.pitch * 0.8, }); - self.game_event(ctx.pos, "minecraft:block_place"); + self.game_event_state(ctx.pos, "minecraft:block_place", placed); PlaceOutcome::Placed { pos: ctx.pos, state: placed, diff --git a/crates/horizon-world/src/level/update.rs b/crates/horizon-world/src/level/update.rs index b981e1a6f..7a0e6d933 100644 --- a/crates/horizon-world/src/level/update.rs +++ b/crates/horizon-world/src/level/update.rs @@ -195,7 +195,19 @@ impl Sim<'_, L> { }); } pub fn game_event(&mut self, pos: BlockPos, event: &'static str) { - self.level.emit(LevelEvent::GameEvent { pos, event }); + self.level.emit(LevelEvent::GameEvent { + pos, + event, + state: None, + }); + } + /// `Level.gameEvent(event, pos, Context.of(state))`. + pub fn game_event_state(&mut self, pos: BlockPos, event: &'static str, state: BlockStateId) { + self.level.emit(LevelEvent::GameEvent { + pos, + event, + state: Some(state), + }); } pub fn block_of(&self, state: BlockStateId) -> BlockId { self.b.table.block(state) @@ -334,7 +346,7 @@ impl Sim<'_, L> { let legacy = self.b.legacy_block(fluid); let destroyed = self.set_block_limit(pos, legacy, 3, limit); if destroyed { - self.game_event(pos, "minecraft:block_destroy"); + self.game_event_state(pos, "minecraft:block_destroy", state); } destroyed }