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/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index f2c51d988..90c715d22 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -317,6 +317,15 @@ pub fn build() -> Dispatcher { let a = d.argument(b, "biome", ArgType::Resource(Resource::Biome)); d.executes(a, "locate.biome"); + // warden_spawn_tracker (clear | set ) + let tracker = d.literal(root, "warden_spawn_tracker"); + d.requires(tracker, GAMEMASTERS); + let clear = d.literal(tracker, "clear"); + d.executes(clear, "warden_spawn_tracker.clear"); + let set = d.literal(tracker, "set"); + let level = d.argument(set, "warning_level", ArgType::Integer { min: 0, max: 4 }); + d.executes(level, "warden_spawn_tracker.set"); + // say / me / msg / list let say = d.literal(root, "say"); d.requires(say, GAMEMASTERS); diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 5f8565e42..5370cb2a9 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), /// `CreakingHeartBlockEntity`: its protector and the hurt emitter. CreakingHeart(Box), /// `BannerBlockEntity`: the pattern layers. @@ -178,6 +180,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:crafter" { return Some(Self::Crafter(Crafter::default())); } @@ -236,6 +241,7 @@ impl BlockEntity { Self::Jukebox(_) => "minecraft:jukebox", Self::Beacon(_) => "minecraft:beacon", Self::Lectern(_) => "minecraft:lectern", + Self::Sculk(s) => s.id(), Self::Banner(_) => "minecraft:banner", Self::Crafter(_) => "minecraft:crafter", Self::CreakingHeart(_) => "minecraft:creaking_heart", @@ -250,6 +256,7 @@ impl BlockEntity { Self::Jukebox(j) => j.record.iter().cloned().collect(), Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), + Self::Sculk(_) => Vec::new(), Self::Banner(_) => Vec::new(), Self::Crafter(c) => c.items.iter().flatten().cloned().collect(), } @@ -263,6 +270,7 @@ impl BlockEntity { | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) + | Self::Sculk(_) | Self::Banner(_) => &[], Self::Crafter(c) => &c.items, Self::CreakingHeart(_) => &[], @@ -277,6 +285,7 @@ impl BlockEntity { | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) + | Self::Sculk(_) | Self::Banner(_) => &mut [], Self::Crafter(c) => &mut c.items, Self::CreakingHeart(_) => &mut [], diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 476b0a243..989933ee9 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -339,6 +339,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)); @@ -620,6 +629,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/fog.rs b/crates/horizon-client/src/fog.rs index 998b3ae8f..4146de4f6 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -185,6 +185,8 @@ pub struct FogInputs<'a> { pub skybox: bool, /// Blindness: (remaining duration ticks, infinite). pub blindness: Option<(i32, bool)>, + /// The darkness effect's blend factor, while the effect is on. + pub darkness: Option, } /// `FogRenderer.setupFog` + `computeFogColor`. @@ -239,6 +241,9 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog } else { 1.0 }; + } else if let Some(blend) = input.darkness { + // DarknessFogEnvironment.getModifiedDarkness. + darkness = darkness.max(blend); } if darkness > 0.0 && !matches!(input.fog_type, FogType::Lava | FogType::PowderSnow) { let brightness = (1.0 - darkness) * (1.0 - darkness); @@ -283,6 +288,15 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog fog.sky_end = distance * 0.8; fog.cloud_end = distance * 0.8; } + _ if input.darkness.is_some() => { + // DarknessFogEnvironment.setupFog: closing in to 15 blocks. + let blend = input.darkness.unwrap_or(0.0); + let distance = rd + (15.0 - rd) * blend; + fog.environmental_start = distance * 0.75; + fog.environmental_end = distance; + fog.sky_end = distance; + fog.cloud_end = distance; + } FogType::Water => { fog.environmental_start = -8.0; let factor = tables @@ -345,6 +359,7 @@ mod tests { thunder: 0.0, skybox: true, blindness: None, + darkness: None, } } #[test] diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c86c68d1a..882905617 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -57,6 +57,7 @@ mod render_control; mod render_tick; mod scoreboard; mod screens; +mod sculk; mod shield; mod sign_edit; mod station_control; @@ -312,14 +313,17 @@ 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; } if let Some(signal) = creaking::heart_signal(self.world, pos) { - return if self.registry.state(_state).is_some_and(|s| { + return if self.registry.state(state).is_some_and(|s| { s.properties .get("creaking_heart_state") .is_some_and(|v| v == "uprooted") @@ -541,6 +545,7 @@ struct Game<'a> { mobs: Vec, arrows: Vec, creatures: creatures::Creatures, + sculk: sculk::SculkState, raiding: raids::Raiding, attack_ticks: u32, last_hurt_by_player: HashSet, @@ -1266,6 +1271,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, @@ -1415,10 +1426,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(()) @@ -1455,6 +1473,12 @@ impl Game<'_> { } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); self.container = Some(key); + self.post_block_game_event( + "minecraft:container_open", + [key.0, key.1, key.2], + Some(horizon_client::mobs::Who::Player), + None, + ); let stat = match &*name { "minecraft:chest" => "open_chest", "minecraft:trapped_chest" => "trigger_trapped_chest", @@ -1576,6 +1600,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. @@ -1673,6 +1700,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(()); @@ -1984,6 +2014,8 @@ impl Game<'_> { } if ticks >= duration { self.using = None; + // Consumable.onConsume. + self.post_entity_event("minecraft:eat", horizon_client::mobs::Who::Player); if let Some((nutrition, saturation)) = info.food && let Some(p) = self.player.as_mut() { @@ -2532,6 +2564,7 @@ impl Game<'_> { } if running { self.tick_block_entities()?; + self.tick_sculk()?; self.tick_brewing_stands()?; } if let Some(r) = &self.renderer { @@ -3113,6 +3146,7 @@ impl Game<'_> { | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) + | BlockEntity::Sculk(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_), ) => {} @@ -3313,6 +3347,7 @@ impl Game<'_> { | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) + | BlockEntity::Sculk(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_), ) => {} @@ -3405,6 +3440,12 @@ impl Game<'_> { } self.craft_size = 2; if let Some(key) = self.container.take() { + self.post_block_game_event( + "minecraft:container_close", + [key.0, key.1, key.2], + Some(horizon_client::mobs::Who::Player), + None, + ); let name = self .res .facts @@ -5778,6 +5819,7 @@ impl Game<'_> { on_ground, ); self.creatures.projectiles.push(arrow); + self.player_projectile_shot(); let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5; self.audio .play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch); @@ -6685,6 +6727,7 @@ impl Game<'_> { self.save_scoreboard(); self.save_bossbars(); self.save_schedule(); + self.save_warden_tracker(); self.sync_level(); self.level.write(&self.world_root)?; self.save_world_state(); @@ -6796,7 +6839,11 @@ impl Game<'_> { } let celestial = if title { self.panorama_geometry() - } else if self.dim == Dim::Overworld { + } else if self.dim == Dim::Overworld + && self.potions.effects.get("darkness").is_none() + && self.potions.effects.get("blindness").is_none() + { + // Camera.doesMobEffectBlockSky: no sun, moon or stars. self.celestial_geometry(&sky) } else if self.dim == Dim::End { self.end_sky_geometry() @@ -6875,6 +6922,7 @@ impl Game<'_> { screen: &screen, game_time: self.world.game_time as f32, ticks: self.ticks, + darkness: self.darkness_lighting(alpha as f32), }; self.renderer.as_mut().ok_or("renderer")?.render(&frame) } @@ -7725,6 +7773,7 @@ pub fn run() -> Result<()> { mobs: Vec::new(), arrows: Vec::new(), creatures: Default::default(), + sculk: Default::default(), raiding: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 89cd02999..b74a65c04 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -563,6 +563,11 @@ impl Game<'_> { self.cmd_scoreboard(id, ctx) } "locate.structure" | "locate.biome" => self.cmd_locate(id, ctx), + "warden_spawn_tracker.clear" | "warden_spawn_tracker.set" => { + let level = Self::int(ctx, "warning_level"); + self.cmd_warden_spawn_tracker(level); + Ok(1) + } "say" | "me" | "msg" => self.cmd_say(id, ctx), "list" => { let names = if ctx.has("uuids") { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 18d0e6b64..4d505b463 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -84,8 +84,10 @@ impl Game<'_> { .chain(super::station_control::HELP) .chain(super::blockctl::HELP) .chain(super::render_control::HELP) + .chain(super::sculk::HELP) .collect::>() }))), "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), + "sculk" => Ok(Some(self.sculk_command(&words)?)), "status" => Ok(Some(self.control_status())), "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3889166ae..a170f9312 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -293,6 +293,7 @@ impl Game<'_> { "on_ground": m.on_ground, "variant": m.extra.variant, "color": m.extra.color, + "warden": horizon_client::mobs::warden::describe(m), "villager": horizon_client::mobs::villager::ext(m).map(|e| serde_json::json!({ "food_level": e.food_level, "inventory": e.inventory.iter().map(|s| format!("{}x{}", s.count, s.item)).collect::>(), @@ -694,6 +695,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); @@ -785,7 +797,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); @@ -928,7 +940,11 @@ impl Game<'_> { m.ai.target = Some(target); } } - MobEvent::Projectile(p) => self.creatures.projectiles.push(p), + MobEvent::Projectile(p) => { + let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]); + self.creatures.projectiles.push(p); + self.projectile_event("minecraft:projectile_shoot", owner, at); + } MobEvent::Spawn(mut m) => { self.next_entity += 1; m.id = self.next_entity; @@ -1035,6 +1051,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::CreakingHurt { home, by_player, @@ -1439,6 +1460,8 @@ impl Game<'_> { return Ok(()); } let atp = [at.x, at.y, at.z]; + // Projectile.onHit: the landing is heard. + self.projectile_event("minecraft:projectile_land", p.owner, atp); let source_kind = match p.kind { ProjectileKind::Arrow { .. } => DamageKind::Arrow, ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => { @@ -2168,6 +2191,7 @@ impl Game<'_> { on_ground, ); self.creatures.projectiles.push(proj); + self.player_projectile_shot(); let sound = match kind { ProjectileKind::Snowball => "minecraft:entity.snowball.throw", ProjectileKind::Egg => "minecraft:entity.egg.throw", diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index 52dc3078e..c51049da8 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -144,6 +144,7 @@ impl Game<'_> { ); arrow.shoot(&mut self.world.random, dir.to_array(), 3.15, 1.0); self.creatures.projectiles.push(arrow); + self.player_projectile_shot(); let pitch = if index == 0 { 1.0 } else { diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 9185252f1..2add475a3 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -326,6 +326,9 @@ impl Game<'_> { fire: bool, ) -> Result<()> { let mut targets = self.exploded_positions(center, radius); + // Explosion.explode: the blast is heard. + let ctx = horizon_client::sculk::Context::default(); + self.post_game_event("minecraft:explode", center, ctx); self.explosion_hurt_entities(center, radius); if interaction != BlockInteraction::Keep { // Util.shuffle(list, level.random) diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 9feff6ef3..163fda0d6 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -120,6 +120,10 @@ impl Game<'_> { Some([x, top.y, z]) } pub(super) fn spawn_bolt(&mut self, at: [f64; 3], visual_only: bool) { + if !visual_only { + let ctx = horizon_client::sculk::Context::default(); + self.post_game_event("minecraft:lightning_strike", at, ctx); + } let r = &mut self.world.random; let seed = r.next_long(); let flashes = r.next_int_bound(3).unwrap_or(0) + 1; diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 00ed63cee..7a3042514 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -170,6 +170,7 @@ impl Game<'_> { return true; } self.using = None; + self.post_entity_event("minecraft:drink", horizon_client::mobs::Who::Player); if ominous { self.drink_ominous_bottle(slot, stack); return true; diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index b978ce1f8..c13973e95 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -88,6 +88,7 @@ impl Game<'_> { thunder, skybox: self.dim == Dim::Overworld, blindness: None, + darkness: self.darkness_fog(), }) } /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs new file mode 100644 index 000000000..e2d985417 --- /dev/null +++ b/crates/horizon-client/src/game/sculk.rs @@ -0,0 +1,1554 @@ +//! 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; + +pub const HELP: &[&str] = &[ + "sculk sculk listeners, the warning level and the darkness blend", + "sculk charge X Y Z AMOUNT a mob dying there with that much experience (the nearest catalyst takes it)", + "sculk warn LEVEL set the player's warden warning level", + "sculk dig end the minute of calm of every warden", +]; + +/// 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, + /// The darkness effect's blend factor, previous and current tick. + darkness: (f32, f32), + /// Who causes the block changes being processed (the player's actions). + pub actor: Option, + ticks: u32, + tracker_loaded: bool, +} +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 + } + + /// The `sculk` control command: listeners and their vibrations, or a + /// test charge for the nearest catalyst. + pub(super) fn sculk_command(&mut self, words: &[&str]) -> Result { + match words.get(1).copied() { + Some("charge") => { + let num = |i: usize| -> Result { + Ok(words.get(i).ok_or("missing argument")?.parse::()?) + }; + let at = [num(2)?, num(3)?, num(4)?]; + let amount = num(5)? as u32; + let taken = self.catalyst_takes_experience(at, |_| amount); + Ok(serde_json::json!({ "ok": true, "taken": taken })) + } + Some("dig") => { + // Let every warden's minute of calm run out. + for m in self + .mobs + .iter_mut() + .filter(|m| m.species() == Species::Warden) + { + warden::expire_dig_cooldown(m); + } + Ok(serde_json::json!({ "ok": true })) + } + Some("warn") => { + let level = words.get(2).ok_or("missing level")?.parse::()?; + self.sculk.tracker.set_warning_level(level); + Ok(serde_json::json!({ "ok": true })) + } + _ => Ok(self.sculk_status()), + } + } + /// The `sculk` control command's listing. + pub(super) fn sculk_status(&self) -> serde_json::Value { + let listeners: Vec = self + .sculk + .index + .iter() + .filter_map(|key| match self.world.block_entities.get(key) { + Some(BlockEntity::Sculk(e)) => Some(serde_json::json!({ + "pos": [key.0, key.1, key.2], + "kind": e.id(), + "current": e.vibration.current.map(|i| i.event), + "travel": e.vibration.travel, + "last_frequency": e.last_frequency, + "warning_level": e.warning_level, + "cursors": e.spreader.cursors.len(), + })), + _ => None, + }) + .collect(); + serde_json::json!({ + "listeners": listeners, + "warning_level": self.sculk.tracker.warning_level, + "cooldown": self.sculk.tracker.cooldown_ticks, + "darkness": self.sculk.darkness.1, + "chunks_known": self.sculk.known.len(), + }) + } + /// `WardenSpawnTrackerCommand`: clear the player's tracker or set its + /// warning level. + pub(super) fn cmd_warden_spawn_tracker(&mut self, level: Option) { + use horizon_client::text::Text; + let key = match level { + Some(level) => { + self.sculk.tracker.set_warning_level(level); + "commands.warden_spawn_tracker.set.success.single" + } + None => { + self.sculk.tracker.reset(); + "commands.warden_spawn_tracker.clear.success.single" + } + }; + if self.ui.rules.bool("send_command_feedback") { + self.system_message(Text::translate( + key, + &[Text::literal(super::chat::PLAYER_NAME)], + )); + } + } + /// `ServerPlayer`'s `warden_spawn_tracker` from the player data. + fn load_warden_tracker(&mut self) { + if self.sculk.tracker_loaded { + return; + } + self.sculk.tracker_loaded = true; + if let Some(tag) = self + .level + .player_extra + .as_ref() + .and_then(|p| p.get("warden_spawn_tracker")) + { + self.sculk.tracker = WardenSpawnTracker::from_nbt(tag); + } + } + /// Write the tracker into the player data being saved. + pub(super) fn save_warden_tracker(&mut self) { + if !self.sculk.tracker_loaded { + return; + } + let tag = self.sculk.tracker.to_nbt(); + let extra = self + .level + .player_extra + .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); + if let horizon_world::nbt::Tag::Compound(map) = extra { + map.insert("warden_spawn_tracker".into(), tag); + } + } + /// Who is causing the block changes being processed. + pub(super) fn sculk_actor(&self) -> Option { + self.sculk.actor + } + + // ---- 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 { + self.context_of_mob(self.mobs.iter().find(|m| m.id == id), id, state) + } + fn context_of_mob(&self, mob: Option<&Mob>, id: u32, state: Option) -> Context { + 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 => { + // The sensor does not hear its own placement or removal. + let own = source_block == [key.0, key.1, key.2] + && matches!(event, "minecraft:block_destroy" | "minecraft:block_place"); + let frequency = sculk::frequency(event); + let calibrated_out = kind == SculkKind::Calibrated && { + let back = self.calibrated_signal(key); + back != 0 && frequency != back + }; + !own && !calibrated_out + && frequency != 0 + && self.res.behaviours.sculk_sensor_can_activate(state) + } + 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.load_warden_tracker(); + self.sculk.tracker.tick(); + self.tick_darkness_blend(); + 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 + }); + // The only player is the one who set it off. + 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 ---- + + /// `MobEffectInstance.BlendState.tick` for the darkness effect: it fades + /// in and out over 22 ticks. + fn tick_darkness_blend(&mut self) { + const BLEND: f32 = 22.0; + let (_, current) = self.sculk.darkness; + let next = match self.potions.effects.get("darkness") { + Some(e) => { + let target = if e.duration == -1 || e.duration > BLEND as i32 { + 1.0 + } else { + 0.0 + }; + current + (target - current).clamp(-1.0 / BLEND, 1.0 / BLEND) + } + None => 0.0, + }; + self.sculk.darkness = (current, next); + } + /// The darkness effect's blend factor at the partial tick. + fn darkness_blend(&self, partial: f32) -> f32 { + let (previous, current) = self.sculk.darkness; + previous + (current - previous) * partial + } + /// The fog's view of the darkness effect, while it is on. + pub(super) fn darkness_fog(&self) -> Option { + self.potions + .effects + .get("darkness") + .map(|_| self.darkness_blend(self.clock.fraction() as f32)) + } + /// `LightmapRenderStateExtractor`: (brightness taken off the gamma + /// option, the pulsing light scale). + pub(super) fn darkness_lighting(&self, partial: f32) -> (f32, f32) { + // options.darknessEffectScale is at its default of 100%. + let modifier = self.darkness_blend(partial); + let pulse = + ((self.ticks as f32 - partial) * std::f32::consts::PI * 0.025).cos() * 0.45 * modifier; + (modifier, pulse.max(0.0)) + } + + /// `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("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 ---- + + /// `Projectile.shoot` / `onHit`: a projectile of `owner` at a position. + pub(super) fn projectile_event( + &mut self, + event: &'static str, + owner: Option, + at: [f64; 3], + ) { + let mut ctx = Context::default(); + if event == "minecraft:projectile_shoot" { + // The shooter is the source of the shot. + ctx = self.who_context(owner, None); + } else { + ctx.owner = owner; + ctx.player = owner == Some(Who::Player) || self.rides_player(owner); + } + self.post_game_event(event, at, ctx); + } + /// The player shot or threw something. + pub(super) fn player_projectile_shot(&mut self) { + if let Some(p) = self.player.as_ref() { + let at = [ + p.position.x, + p.position.y + f64::from(self.eye), + p.position.z, + ]; + self.projectile_event("minecraft:projectile_shoot", Some(Who::Player), at); + } + } + + /// 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.context_of_mob(Some(m), 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/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index d4138ff83..3297fe96e 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -37,6 +37,9 @@ impl Game<'_> { /// `new PrimedTnt(level, x + 0.5, y, z + 0.5, owner)`; `short` applies /// `wasExploded`'s random short fuse. Plays `entity.tnt.primed` for primes. pub(super) fn spawn_primed_tnt(&mut self, pos: BlockPos, short: bool) { + // PrimedTnt: the fuse is lit. + let who = self.sculk_actor(); + self.post_block_game_event("minecraft:prime_fuse", [pos.x, pos.y, pos.z], who, None); let r = &mut self.world.random; let rot = r.next_double() * f64::from(std::f32::consts::TAU); let position = Vec3::new( diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index e2cd00e34..66a0fd93a 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -177,6 +177,7 @@ impl Game<'_> { returning: 0, creative_only: self.creative, }); + self.player_projectile_shot(); self.audio .play("minecraft:item.trident.throw", at, 1.0, 1.0); } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 44b76e51f..ce51c2475 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -77,6 +77,9 @@ pub struct Frame<'a> { pub screen: &'a [crate::screen_effects::ScreenQuad], pub game_time: f32, pub ticks: u64, + /// The darkness effect on the lightmap: the brightness it takes off the + /// gamma option and the pulsing scale subtracted from the light. + pub darkness: (f32, f32), } pub struct Renderer { instance: wgpu::Instance, @@ -1186,7 +1189,11 @@ impl Renderer { } }; self.animate(frame.ticks); - self.update_lightmap(&frame.sky, 0.0, self.gamma); + self.update_lightmap( + &frame.sky, + frame.darkness.1, + (self.gamma - frame.darkness.0).max(0.0), + ); let view_proj = self.view_projection(frame); let aspect = self.config.width as f32 / self.config.height.max(1) as f32; let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians()); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 8998a365d..09c1ecbb0 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -67,6 +67,7 @@ pub mod save; pub mod scoreboard; pub mod scoreboard_cmd; 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 832e1c155..0390a9289 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -39,6 +39,7 @@ pub mod tame; pub mod undead; pub mod vex; pub mod villager; +pub mod warden; pub mod witch; pub mod wither; mod world; @@ -338,6 +339,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)] @@ -392,6 +394,7 @@ impl Damage { | DamageKind::Magic | DamageKind::InWall | DamageKind::Generic + | DamageKind::SonicBoom ) } pub fn is_fire(&self) -> bool { @@ -479,6 +482,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>, /// A raider's patrol and raid state. pub raider: Option>, /// A villager's raid activity and gossip. @@ -716,6 +721,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, + }, /// A creaking bound to the heart at `home` was hurt (`creakingHurt` when a player did it). CreakingHurt { home: [i32; 3], diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 29d1270fb..6081bf5ab 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, Creaking, } pub fn family(s: Species) -> Family { @@ -132,6 +133,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, } @@ -171,6 +173,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), Family::Creaking => super::creaking::register(m), } super::raider::register(m); @@ -381,6 +384,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", @@ -551,6 +559,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, _ => {} @@ -578,6 +587,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), @@ -600,7 +610,8 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { /// Mob.checkDespawn (players are the only despawn reference). fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { let creature = m.kind.category == "creature"; - if m.persistent || creature && m.kind.flags.animal { + // Warden.removeWhenFarAway is false. + if m.persistent || m.species() == Species::Warden || creature && m.kind.flags.animal { m.ai.no_action_time = 0; return true; } @@ -648,6 +659,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 @@ -689,6 +701,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { Species::Allay if m.extra.tame && source.attacker == Some(Who::Player) => false, Species::Creaking => super::creaking::accepts_damage(m, source), 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 @@ -705,6 +718,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 ae44a2630..703f82479 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, Creaking, Camel, @@ -346,6 +347,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::Creaking => super::creaking::anim(m, s, p, w_anims), Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 00ebfb71a..7caabb812 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 d640b6973..131837d93 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -774,7 +774,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 266d5baa1..40a455f91 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 1d38d4789..2f9b04220 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, Creaking, } /// Baby bounding boxes (each class's BABY_DIMENSIONS). @@ -1163,6 +1164,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]) @@ -1371,6 +1386,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..4df5ebf19 --- /dev/null +++ b/crates/horizon-client/src/mobs/warden.rs @@ -0,0 +1,1666 @@ +//! 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 + && 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(); + } +} +/// Test aid: the minute of calm ran out. +pub fn expire_dig_cooldown(m: &mut Mob) { + if let Some(st) = m.extra.warden.as_mut() { + st.dig_cooldown = None; + st.attack_target = None; + st.roar_target = None; + } +} +/// The warden's state for the control socket. +pub fn describe(m: &Mob) -> Option { + let st = m.extra.warden.as_ref()?; + let anger: Vec = st + .anger + .suspects() + .iter() + .map(|w| format!("{w:?}={}", st.anger.anger_of(*w))) + .collect(); + Some(serde_json::json!({ + "pose": format!("{:?}", pose(m)), + "activity": format!("{:?}", st.activity), + "anger_level": format!("{:?}", anger_level(m)), + "anger": anger, + "attack_target": st.attack_target.map(|t| format!("{t:?}")), + "roar_target": st.roar_target.map(|t| format!("{t:?}")), + "disturbance": st.disturbance.map(|(p, _)| p), + "walk": st.walk.is_some(), + "dig_cooldown": st.dig_cooldown.map(|t| t - i64::from(m.age)), + "sniff_cooldown": st.sniff_cooldown.map(|t| t - i64::from(m.age)), + "vibration": st.vibration.current.map(|i| i.event), + })) +} +/// `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 { + in_brain: true, + ..Warden::default() + }; + // Set during the brain: present for exactly the ttl. + 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 5e075d29e..4d468a64c 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -120,6 +120,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. @@ -139,8 +145,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], /// `TrailParticleOption`: the point it flies to and how many ticks it takes. pub trail: Option<([f64; 3], i32)>, } @@ -151,9 +160,44 @@ impl ParticleOptions { block: None, color: [1.0; 4], scale: 1.0, + to_color: [1.0, 0.0, 0.0], trail: None, } } + /// `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) + } + } /// `TrailParticleOption(target, color, duration)`. pub fn trail(target: [f64; 3], rgb: u32, duration: i32) -> Self { Self { @@ -205,6 +249,8 @@ enum Size { Lava, Portal, ReversePortal, + /// `ShriekParticle.getQuadSize`. + Shriek, } #[derive(Clone, Copy, Debug, PartialEq)] enum Light { @@ -278,6 +324,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], + }, /// `TrailParticle`: eases towards its target over its lifetime. Trail { target: [f64; 3], @@ -532,6 +595,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), } } } @@ -676,6 +740,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); @@ -1432,12 +1517,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; @@ -1491,6 +1581,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; @@ -2185,6 +2338,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::Trail { target } => { p.previous = p.position; let age = p.age; @@ -2455,6 +2651,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(-std::f32::consts::FRAC_PI_3)), + Some(Quat::from_euler( + glam::EulerRot::YXZ, + -std::f32::consts::PI, + std::f32::consts::FRAC_PI_3, + 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); @@ -2476,7 +2724,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], @@ -2484,20 +2732,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 4c2df5d6c..e949eb8ef 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -404,6 +404,7 @@ pub fn encode_block_entity( entries.push(("Page", Tag::Int(l.page))); } } + BlockEntity::Sculk(s) => entries.extend(s.to_nbt()), BlockEntity::Crafter(c) => { entries.push(("Items", encode_items(&c.items))); entries.push(( @@ -521,6 +522,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain }; } BlockEntity::Sign(sign) => sign.decode(tag), + BlockEntity::Sculk(s) => s.load(tag), BlockEntity::Crafter(c) => { for (slot, item) in decode_items(tag.get("Items"), 9).into_iter().enumerate() { c.items[slot] = item; diff --git a/crates/horizon-client/src/sculk.rs b/crates/horizon-client/src/sculk.rs new file mode 100644 index 000000000..e7eb4b7ce --- /dev/null +++ b/crates/horizon-client/src/sculk.rs @@ -0,0 +1,887 @@ +//! 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 { + current: tag.get("event").and_then(info_from_nbt), + ..Self::default() + }; + 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/data.rs b/crates/horizon-world/src/level/data.rs index e66b086e6..b97ade119 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -355,6 +355,11 @@ named_blocks! { campfire = "campfire", light = "light", sculk_sensor = "sculk_sensor", + calibrated_sculk_sensor = "calibrated_sculk_sensor", + sculk_shrieker = "sculk_shrieker", + sculk_catalyst = "sculk_catalyst", + sculk = "sculk", + sculk_vein = "sculk_vein", lectern = "lectern", target = "target", daylight_detector = "daylight_detector", @@ -563,6 +568,8 @@ props! { side_chain = "side_chain", copper_golem_pose = "copper_golem_pose", sculk_sensor_phase = "sculk_sensor_phase", + shrieking = "shrieking", + can_summon = "can_summon", potent_sulfur_state = "potent_sulfur_state", } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 1a0cdaa20..1c617e937 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -114,6 +114,7 @@ mod place; mod query; mod rails; mod redstone; +pub mod sculk; mod shapes; mod signals; mod speleothem; @@ -252,8 +253,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 401288c3e..9ab3f8917 100644 --- a/crates/horizon-world/src/level/place.rs +++ b/crates/horizon-world/src/level/place.rs @@ -1519,7 +1519,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/sculk.rs b/crates/horizon-world/src/level/sculk.rs new file mode 100644 index 000000000..a831f2151 --- /dev/null +++ b/crates/horizon-world/src/level/sculk.rs @@ -0,0 +1,870 @@ +//! Sculk: the sensor's phases, the shrieker and catalyst blocks, and the +//! level `SculkSpreader` with the sculk, sculk vein and default charge-cursor +//! behaviours (`SculkBlock`, `SculkVeinBlock`, `SculkBehaviour`). +use super::{ + Behaviours, LevelAccess, LevelEvent, Sim, Ticks, + classes::Class, + update::{above, below, rel}, +}; +use crate::{fluid::FluidState, registry::BlockStateId}; +use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; + +/// `SculkSensorBlock.ACTIVE_TICKS` (calibrated sensors use 10). +pub const SENSOR_ACTIVE_TICKS: i32 = 30; +pub const CALIBRATED_ACTIVE_TICKS: i32 = 10; +/// `SculkSensorBlock.COOLDOWN_TICKS`. +pub const SENSOR_COOLDOWN_TICKS: i32 = 10; +/// `SculkShriekerBlockEntity` shrieking time. +pub const SHRIEKING_TICKS: i32 = 90; +/// `SculkCatalystBlockEntity.CatalystListener.PULSE_TICKS`. +pub const PULSE_TICKS: i32 = 8; + +// SculkSpreader.createLevelSpreader. +const GROWTH_SPAWN_COST: i32 = 10; +const NO_GROWTH_RADIUS: i32 = 4; +const CHARGE_DECAY_RATE: i32 = 10; +const ADDITIONAL_DECAY_RATE: i32 = 5; +const MAX_CURSORS: usize = 32; +const MAX_CHARGE: i32 = 1000; +const MAX_CURSOR_DISTANCE: i32 = 1024; + +/// One `SculkSpreader.ChargeCursor`. +#[derive(Clone, Debug, PartialEq)] +pub struct ChargeCursor { + pub pos: BlockPos, + pub charge: i32, + pub update_delay: i32, + pub decay_delay: i32, + /// The faces of the block the cursor last moved onto, if any. + pub facings: Option>, +} +impl ChargeCursor { + pub fn new(pos: BlockPos, charge: i32) -> Self { + Self { + pos, + charge, + update_delay: 0, + decay_delay: 1, + facings: None, + } + } +} +/// A catalyst's `SculkSpreader` (the level configuration). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SculkSpreader { + pub cursors: Vec, +} +impl SculkSpreader { + /// `addCursors`: charge in chunks of at most 1000, at most 32 cursors. + pub fn add_cursors(&mut self, start: BlockPos, mut charge: i32) { + while charge > 0 { + let current = charge.min(MAX_CHARGE); + self.add_cursor(ChargeCursor::new(start, current)); + charge -= current; + } + } + pub fn add_cursor(&mut self, cursor: ChargeCursor) { + if self.cursors.len() < MAX_CURSORS { + self.cursors.push(cursor); + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Behaviour { + Default, + Sculk, + Vein, +} +#[derive(Clone, Copy)] +enum Spread { + SamePosition, + SamePlane, + WrapAround, +} +const ALL_SPREADS: [Spread; 3] = [Spread::SamePosition, Spread::SamePlane, Spread::WrapAround]; + +/// `MultifaceBlock.pack`: the faces as bits of their ordinals. +pub fn pack_faces(faces: &[Direction]) -> i32 { + faces.iter().fold(0, |code, d| code | 1 << *d as i32) +} +/// `MultifaceBlock.unpack`. +pub fn unpack_faces(data: i32) -> Vec { + Direction::ALL + .into_iter() + .filter(|d| data & (1 << *d as i32) != 0) + .collect() +} + +impl Sim<'_, L> { + fn sculk_rand(&mut self, bound: i32) -> i32 { + self.random().next_int_bound(bound).unwrap_or(0) + } + fn sculk_in_tag(&self, state: BlockStateId, tag: &str) -> bool { + self.b.tag(tag).is_some_and(|set| self.b.in_set(state, set)) + } + fn sculk_sound(&mut self, pos: BlockPos, sound: &str, volume: f32, pitch: f32) { + self.emit(LevelEvent::Sound { + pos, + sound: sound.into(), + volume, + pitch, + }); + } + + // ---- sensors ---- + + /// `SculkSensorBlock.canActivate`. + pub(crate) fn sensor_phase(&self, state: BlockStateId) -> &'static str { + match self.b.table.text(state, self.b.props.sculk_sensor_phase) { + "active" => "active", + "cooldown" => "cooldown", + _ => "inactive", + } + } + fn sensor_update_neighbours(&mut self, pos: BlockPos, state: BlockStateId) { + let block = self.b.block(state); + self.update_neighbors_at(pos, block); + self.update_neighbors_at(below(pos), block); + } + /// `SculkSensorBlock.tick`. + pub(crate) fn sculk_sensor_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + match self.sensor_phase(state) { + "active" => self.sculk_sensor_deactivate(pos, state), + "cooldown" => { + let next = b + .table + .set_text(state, b.props.sculk_sensor_phase, "inactive"); + self.set_block_and_update(pos, next); + if !b.table.bool(state, b.props.waterlogged) { + let pitch = self.random().next_float() * 0.2 + 0.8; + self.sculk_sound( + pos, + "minecraft:block.sculk_sensor.clicking_stop", + 1.0, + pitch, + ); + } + } + _ => {} + } + } + /// `SculkSensorBlock.deactivate`. + pub(crate) fn sculk_sensor_deactivate(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + let next = b.table.set_int( + b.table + .set_text(state, b.props.sculk_sensor_phase, "cooldown"), + b.props.power, + 0, + ); + self.set_block_and_update(pos, next); + let block = b.block(state); + self.schedule_tick(pos, block, SENSOR_COOLDOWN_TICKS); + self.sensor_update_neighbours(pos, state); + } + /// `SculkSensorBlock.activate` without the resonance and the tendril + /// event, which need the source entity. + pub(crate) fn sculk_sensor_activate( + &mut self, + pos: BlockPos, + state: BlockStateId, + power: i32, + active_ticks: i32, + ) { + let b = self.b; + let next = b.table.set_int( + b.table + .set_text(state, b.props.sculk_sensor_phase, "active"), + b.props.power, + power, + ); + self.set_block_and_update(pos, next); + let block = b.block(state); + self.schedule_tick(pos, block, active_ticks); + self.sensor_update_neighbours(pos, state); + } + /// The activation sound, played after the tendril event. + pub(crate) fn sculk_sensor_click(&mut self, pos: BlockPos, state: BlockStateId) { + if !self.b.table.bool(state, self.b.props.waterlogged) { + let pitch = self.random().next_float() * 0.2 + 0.8; + self.sculk_sound(pos, "minecraft:block.sculk_sensor.clicking", 1.0, pitch); + } + } + + // ---- shrieker and catalyst ---- + + /// `SculkShriekerBlock.tick`: the shriek ends and the block responds. + pub(crate) fn sculk_shrieker_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.bool(state, b.props.shrieking) { + let next = b.table.set_bool(state, b.props.shrieking, false); + self.set_block_and_update(pos, next); + self.emit(LevelEvent::BlockEvent { + pos, + state: next, + kind: "shrieker_respond", + }); + } + } + /// `SculkCatalystBlock.tick`. + pub(crate) fn sculk_catalyst_tick(&mut self, pos: BlockPos, state: BlockStateId) { + let b = self.b; + if b.table.bool(state, b.props.bloom) { + let next = b.table.set_bool(state, b.props.bloom, false); + self.set_block_and_update(pos, next); + } + } + + // ---- the spreader ---- + + fn sculk_behaviour(&self, state: BlockStateId) -> Behaviour { + let block = self.b.block(state); + if block == self.b.named.sculk { + Behaviour::Sculk + } else if block == self.b.named.sculk_vein { + Behaviour::Vein + } else { + Behaviour::Default + } + } + fn is_vein(&self, state: BlockStateId) -> bool { + self.b.block(state) == self.b.named.sculk_vein + } + fn vein_has_face(&self, state: BlockStateId, face: Direction) -> bool { + self.is_vein(state) && self.multiface_has_face(state, face) + } + fn vein_with_face(&self, state: BlockStateId, face: Direction, value: bool) -> BlockStateId { + self.b + .table + .set_bool(state, self.direction_prop(face), value) + } + fn available_faces(&self, state: BlockStateId) -> Vec { + if !self.b.instance_of(state, Class::Multiface) { + return Vec::new(); + } + Direction::ALL + .into_iter() + .filter(|d| self.multiface_has_face(state, *d)) + .collect() + } + fn is_sculk_source(&self, state: BlockStateId) -> bool { + self.sculk_behaviour(state) != Behaviour::Default + } + + /// `SculkSpreader.updateCursors`. + pub(crate) fn sculk_update_cursors( + &mut self, + spreader: &mut SculkSpreader, + origin: BlockPos, + spread_veins: bool, + ) { + if spreader.cursors.is_empty() { + return; + } + let cursors = std::mem::take(&mut spreader.cursors); + let mut processed: Vec = Vec::new(); + // The cursor each position merges into (index into `processed`). + let mut mergeable: Vec<(BlockPos, usize)> = Vec::new(); + let mut charge_map: Vec<(BlockPos, i32)> = Vec::new(); + for mut cursor in cursors { + let distance = (cursor.pos.x.wrapping_sub(origin.x).wrapping_abs()) + .max(cursor.pos.y.wrapping_sub(origin.y).wrapping_abs()) + .max(cursor.pos.z.wrapping_sub(origin.z).wrapping_abs()); + if distance > MAX_CURSOR_DISTANCE { + continue; + } + self.sculk_cursor_update(&mut cursor, origin, spread_veins); + if cursor.charge <= 0 { + self.level_event(3006, cursor.pos, 0); + continue; + } + let pos = cursor.pos; + match charge_map.iter_mut().find(|(p, _)| *p == pos) { + Some(entry) => entry.1 += cursor.charge, + None => charge_map.push((pos, cursor.charge)), + } + match mergeable.iter().position(|(p, _)| *p == pos) { + None => { + mergeable.push((pos, processed.len())); + processed.push(cursor); + } + Some(slot) => { + let index = mergeable[slot].1; + if cursor.charge + processed[index].charge <= MAX_CHARGE { + // mergeWith + processed[index].charge += cursor.charge; + processed[index].update_delay = + processed[index].update_delay.min(cursor.update_delay); + } else { + let smaller = cursor.charge < processed[index].charge; + processed.push(cursor); + if smaller { + mergeable[slot].1 = processed.len() - 1; + } + } + } + } + } + for (pos, charge) in charge_map { + let faces = mergeable + .iter() + .find(|(p, _)| *p == pos) + .and_then(|(_, i)| processed[*i].facings.clone()); + if charge > 0 + && let Some(faces) = faces + { + let particles = ((f64::from(charge) + 1.0).ln() as f32 / 2.3) as i32 + 1; + let data = (particles << 6) + pack_faces(&faces); + self.level_event(3006, pos, data); + } + } + spreader.cursors = processed; + } + + /// `ChargeCursor.update`. + fn sculk_cursor_update(&mut self, cursor: &mut ChargeCursor, origin: BlockPos, veins: bool) { + // shouldUpdate: charge left and the origin's chunk is ticking. + if cursor.charge <= 0 || !self.level.is_ticking_chunk(origin.chunk()) { + return; + } + if cursor.update_delay > 0 { + cursor.update_delay -= 1; + return; + } + let mut state = self.state(cursor.pos); + let mut behaviour = self.sculk_behaviour(state); + if veins && self.sculk_attempt_spread_vein(behaviour, cursor.pos, state, &cursor.facings) { + // SculkBlock.canChangeBlockStateOnSpread is false. + if behaviour != Behaviour::Sculk { + state = self.state(cursor.pos); + behaviour = self.sculk_behaviour(state); + } + self.sculk_sound(cursor.pos, "minecraft:block.sculk.spread", 1.0, 1.0); + } + cursor.charge = self.sculk_attempt_use_charge(behaviour, cursor, origin, veins); + if cursor.charge <= 0 { + self.sculk_on_discharged(behaviour, state, cursor.pos); + return; + } + let transfer = self.sculk_valid_movement(cursor.pos); + if let Some(target) = transfer { + self.sculk_on_discharged(behaviour, state, cursor.pos); + cursor.pos = target; + state = self.state(target); + } + if self.is_sculk_source(state) { + cursor.facings = Some(self.available_faces(state)); + } + cursor.decay_delay = match behaviour { + Behaviour::Default => (cursor.decay_delay - 1).max(0), + _ => 1, + }; + cursor.update_delay = 1; + } + + /// `SculkBehaviour.attemptSpreadVein` (the default behaviour's override + /// regrows veins or spreads in the same space). + fn sculk_attempt_spread_vein( + &mut self, + behaviour: Behaviour, + pos: BlockPos, + state: BlockStateId, + facings: &Option>, + ) -> bool { + if behaviour == Behaviour::Default { + match facings { + None => { + let current = self.state(pos); + return self.sculk_spread_all(current, pos, &[Spread::SamePosition]) > 0; + } + Some(faces) if !faces.is_empty() => { + let b = self.b; + let water = b.is_block(state, b.named.water) && b.fluid(state).is_source(); + if !b.is_air(state) && !water { + return false; + } + return self.sculk_regrow(pos, state, faces); + } + Some(_) => {} + } + } + self.sculk_spread_all(state, pos, &ALL_SPREADS) > 0 + } + /// `SculkVeinBlock.regrow`. + fn sculk_regrow(&mut self, pos: BlockPos, existing: BlockStateId, faces: &[Direction]) -> bool { + let b = self.b; + let mut state = b.default_of(b.named.sculk_vein); + let mut any = false; + for &face in faces { + if b.multiface_can_attach(self.state(rel(pos, face)), face) { + state = self.vein_with_face(state, face, true); + any = true; + } + } + if !any { + return false; + } + if b.fluid(existing) != FluidState::EMPTY { + state = b.table.set_bool(state, b.props.waterlogged, true); + } + self.set_block_and_update(pos, state); + true + } + /// `MultifaceSpreader.spreadAll` with the sculk vein configuration. + fn sculk_spread_all(&mut self, state: BlockStateId, pos: BlockPos, types: &[Spread]) -> i64 { + let other_source = !self.is_vein(state); + let mut count = 0; + for face in Direction::ALL { + if !(other_source || self.vein_has_face(state, face)) { + continue; + } + for direction in Direction::ALL { + if crate::level::query::axis_of(direction) == crate::level::query::axis_of(face) { + continue; + } + if !(other_source + || (self.vein_has_face(state, face) && !self.vein_has_face(state, direction))) + { + continue; + } + let mut target = None; + for kind in types { + let candidate = match kind { + Spread::SamePosition => (pos, direction), + Spread::SamePlane => (rel(pos, direction), face), + Spread::WrapAround => { + (rel(rel(pos, direction), face), direction.opposite()) + } + }; + if self.sculk_can_spread_into(pos, candidate.0, candidate.1) { + target = Some(candidate); + break; + } + } + let Some((target, face_to)) = target else { + continue; + }; + let old = self.state(target); + let Some(new) = self.sculk_state_for_placement(old, target, face_to) else { + continue; + }; + if self.set_block(target, new, 2) { + count += 1; + } + } + } + count + } + fn sculk_valid_for_placement(&self, old: BlockStateId, pos: BlockPos, face: Direction) -> bool { + if self.vein_has_face(old, face) { + return false; + } + self.b + .multiface_can_attach(self.state(rel(pos, face)), face) + } + /// `MultifaceBlock.getStateForPlacement` for the sculk vein. + fn sculk_state_for_placement( + &self, + old: BlockStateId, + pos: BlockPos, + face: Direction, + ) -> Option { + if !self.sculk_valid_for_placement(old, pos, face) { + return None; + } + let b = self.b; + let base = if self.is_vein(old) { + old + } else if b.fluid(old) == FluidState::WATER { + b.table + .set_bool(b.default_of(b.named.sculk_vein), b.props.waterlogged, true) + } else { + b.default_of(b.named.sculk_vein) + }; + Some(self.vein_with_face(base, face, true)) + } + /// `SculkVeinSpreaderConfig.canSpreadInto` (with the default config). + fn sculk_can_spread_into(&self, source: BlockPos, target: BlockPos, face: Direction) -> bool { + let b = self.b; + let existing = self.state(target); + let against = self.state(rel(target, face)); + let against_block = b.block(against); + if against_block == b.named.sculk + || against_block == b.named.sculk_catalyst + || against_block == b.named.moving_piston + { + return false; + } + let manhattan = + (source.x - target.x).abs() + (source.y - target.y).abs() + (source.z - target.z).abs(); + if manhattan == 2 { + let neighbour = rel(source, face.opposite()); + if b.is_face_sturdy(self.state(neighbour), face) { + return false; + } + } + let fluid = b.fluid(existing); + if fluid != FluidState::EMPTY && !(b.is_block(existing, b.named.water) && fluid.is_source()) + { + return false; + } + if self.sculk_in_tag(existing, "minecraft:fire") { + return false; + } + let replaceable = b.is_replaceable(existing) + || b.is_air(existing) + || self.is_vein(existing) + || (b.is_block(existing, b.named.water) && fluid.is_source()); + replaceable && self.sculk_valid_for_placement(existing, target, face) + } + + /// `SculkBehaviour.attemptUseCharge` per behaviour. + fn sculk_attempt_use_charge( + &mut self, + behaviour: Behaviour, + cursor: &ChargeCursor, + origin: BlockPos, + veins: bool, + ) -> i32 { + let charge = cursor.charge; + match behaviour { + Behaviour::Default => { + if cursor.decay_delay > 0 { + charge + } else { + 0 + } + } + Behaviour::Vein => { + if veins && self.sculk_place_sculk(cursor.pos) { + charge - 1 + } else if self.sculk_rand(CHARGE_DECAY_RATE) == 0 { + (charge as f32 * 0.5).floor() as i32 + } else { + charge + } + } + Behaviour::Sculk => { + if charge == 0 || self.sculk_rand(CHARGE_DECAY_RATE) != 0 { + return charge; + } + let pos = cursor.pos; + let dist_sqr = f64::from( + (pos.x - origin.x).pow(2) + + (pos.y - origin.y).pow(2) + + (pos.z - origin.z).pow(2), + ); + let close = dist_sqr < f64::from(NO_GROWTH_RADIUS * NO_GROWTH_RADIUS); + if !close && self.sculk_can_place_growth(pos) { + if self.sculk_rand(GROWTH_SPAWN_COST) < charge { + let growth_pos = above(pos); + let growth = self.sculk_random_growth(growth_pos); + self.set_block_and_update(growth_pos, growth); + let sounds = self.b.data(growth).sounds.clone(); + self.emit(LevelEvent::Sound { + pos, + sound: sounds.place.clone(), + volume: 1.0, + pitch: 1.0, + }); + } + return (charge - GROWTH_SPAWN_COST).max(0); + } + if self.sculk_rand(ADDITIONAL_DECAY_RATE) != 0 { + return charge; + } + let penalty = if close { + 1 + } else { + // getDecayPenalty + let outer = (dist_sqr.sqrt() as f32 - NO_GROWTH_RADIUS as f32).powi(2); + let reach = (24 - NO_GROWTH_RADIUS) * (24 - NO_GROWTH_RADIUS); + let factor = 1.0f32.min(outer / reach as f32); + 1.max((charge as f32 * factor * 0.5) as i32) + }; + charge - penalty + } + } + } + /// `SculkBlock.getRandomGrowthState` (not for world generation). + fn sculk_random_growth(&mut self, pos: BlockPos) -> BlockStateId { + let b = self.b; + let state = if self.sculk_rand(11) == 0 { + b.default_of(b.named.sculk_shrieker) + } else { + b.default_of(b.named.sculk_sensor) + }; + if self.fluid_at(pos) != FluidState::EMPTY { + b.table.set_bool(state, b.props.waterlogged, true) + } else { + state + } + } + /// `SculkBlock.canPlaceGrowth`. + fn sculk_can_place_growth(&self, pos: BlockPos) -> bool { + let b = self.b; + let state_above = self.state(above(pos)); + let open = b.is_air(state_above) + || (b.is_block(state_above, b.named.water) && b.fluid(state_above).is_source()); + if !open { + return false; + } + let mut matched = 0; + for dz in -4..=4 { + for dy in 0..=2 { + for dx in -4..=4 { + let state = self.state(pos.offset(dx, dy, dz)); + if self.sculk_in_tag(state, "minecraft:sculk_growth_inhibitors") { + matched += 1; + if matched >= 3 { + return false; + } + } + } + } + } + true + } + /// `SculkVeinBlock.attemptPlaceSculk`. + fn sculk_place_sculk(&mut self, pos: BlockPos) -> bool { + let state = self.state(pos); + let mut directions = Direction::ALL; + for i in (2..=directions.len()).rev() { + let swap = self.sculk_rand(i as i32) as usize; + directions.swap(i - 1, swap); + } + for support in directions { + if !self.vein_has_face(state, support) { + continue; + } + let support_pos = rel(pos, support); + let support_state = self.state(support_pos); + if !self.sculk_in_tag(support_state, "minecraft:sculk_replaceable") { + continue; + } + let default_sculk = self.b.default_of(self.b.named.sculk); + self.set_block_and_update(support_pos, default_sculk); + self.sculk_sound(support_pos, "minecraft:block.sculk.spread", 1.0, 1.0); + self.sculk_spread_all(default_sculk, support_pos, &ALL_SPREADS); + let skip = support.opposite(); + for direction in Direction::ALL { + if direction == skip { + continue; + } + let vein_pos = rel(support_pos, direction); + let possible = self.state(vein_pos); + if self.is_vein(possible) { + self.sculk_on_discharged(Behaviour::Vein, possible, vein_pos); + } + } + return true; + } + false + } + /// `SculkVeinBlock.onDischarged`. + fn sculk_on_discharged(&mut self, behaviour: Behaviour, state: BlockStateId, pos: BlockPos) { + if behaviour != Behaviour::Vein || !self.is_vein(state) { + return; + } + let b = self.b; + let mut state = state; + for direction in Direction::ALL { + if self.multiface_has_face(state, direction) + && b.is_block(self.state(rel(pos, direction)), b.named.sculk) + { + state = self.vein_with_face(state, direction, false); + } + } + if !Direction::ALL + .into_iter() + .any(|d| self.multiface_has_face(state, d)) + { + state = if self.fluid_at(pos) == FluidState::EMPTY { + b.default_of(b.named.air) + } else { + b.default_of(b.named.water) + }; + } + self.set_block_and_update(pos, state); + } + /// `ChargeCursor.getValidMovementPos`. + fn sculk_valid_movement(&mut self, pos: BlockPos) -> Option { + let mut offsets = Vec::with_capacity(18); + for z in -1..=1 { + for y in -1..=1 { + for x in -1..=1 { + if (x == 0 || y == 0 || z == 0) && (x, y, z) != (0, 0, 0) { + offsets.push([x, y, z]); + } + } + } + } + for i in (2..=offsets.len()).rev() { + let swap = self.sculk_rand(i as i32) as usize; + offsets.swap(i - 1, swap); + } + let b = self.b; + let mut best = pos; + for o in offsets { + let neighbour = pos.offset(o[0], o[1], o[2]); + let transferee = self.state(neighbour); + if self.sculk_behaviour(transferee) == Behaviour::Default + || !self.sculk_unobstructed_move(pos, neighbour) + { + continue; + } + best = neighbour; + // SculkVeinBlock.hasSubstrateAccess + if self.is_vein(transferee) + && Direction::ALL.into_iter().any(|d| { + self.multiface_has_face(transferee, d) + && self.sculk_in_tag( + self.state(rel(neighbour, d)), + "minecraft:sculk_replaceable", + ) + }) + { + break; + } + } + let _ = b; + (best != pos).then_some(best) + } + fn sculk_unobstructed_move(&self, from: BlockPos, to: BlockPos) -> bool { + let manhattan = (from.x - to.x).abs() + (from.y - to.y).abs() + (from.z - to.z).abs(); + if manhattan == 1 { + return true; + } + let delta = [to.x - from.x, to.y - from.y, to.z - from.z]; + let dir_x = if delta[0] < 0 { + Direction::West + } else { + Direction::East + }; + let dir_y = if delta[1] < 0 { + Direction::Down + } else { + Direction::Up + }; + let dir_z = if delta[2] < 0 { + Direction::North + } else { + Direction::South + }; + let (a, c) = if delta[0] == 0 { + (dir_y, dir_z) + } else if delta[1] == 0 { + (dir_x, dir_z) + } else { + (dir_x, dir_y) + }; + let free = |direction: Direction| { + let test = rel(from, direction); + !self + .b + .is_face_sturdy(self.state(test), direction.opposite()) + }; + free(a) || free(c) + } +} + +impl Behaviours { + /// `SculkSensorBlock.canActivate`: the sensor is inactive. + pub fn sculk_sensor_can_activate(&self, state: BlockStateId) -> bool { + self.table.text(state, self.props.sculk_sensor_phase) == "inactive" + } + /// The sensor's phase (`inactive`, `active` or `cooldown`). + pub fn sculk_sensor_active(&self, state: BlockStateId) -> bool { + self.table.text(state, self.props.sculk_sensor_phase) == "active" + } + /// `SculkSensorBlock.activate` (the state, its ticks and the redstone + /// update); the caller sends the tendril and resonance events. + pub fn sculk_sensor_activate( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + power: i32, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + let active_ticks = if self.block(state) == self.named.calibrated_sculk_sensor { + CALIBRATED_ACTIVE_TICKS + } else { + SENSOR_ACTIVE_TICKS + }; + sim.sculk_sensor_activate(pos, state, power, active_ticks); + } + /// The click sound after an activation. + pub fn sculk_sensor_click( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + sim.sculk_sensor_click(pos, state); + } + /// `CalibratedSculkSensorBlockEntity.VibrationUser.getBackSignal`. + pub fn calibrated_back_signal( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) -> i32 { + let sim = self.sim(level, ticks); + let state = sim.state(pos); + let direction = self.facing(state).opposite(); + sim.signal(rel(pos, direction), direction) + } + /// `SculkCatalystBlockEntity.CatalystListener.bloom`'s block half. + pub fn sculk_catalyst_bloom( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + if self.block(state) != self.named.sculk_catalyst { + return; + } + let next = self.table.set_bool(state, self.props.bloom, true); + sim.set_block_and_update(pos, next); + let block = self.block(state); + sim.schedule_tick(pos, block, PULSE_TICKS); + } + /// `SculkShriekerBlockEntity.shriek`'s block half: `shrieking` for 90 ticks. + pub fn sculk_shrieker_shriek( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + if self.block(state) != self.named.sculk_shrieker { + return; + } + let next = self.table.set_bool(state, self.props.shrieking, true); + sim.set_block(pos, next, 2); + let block = self.block(state); + sim.schedule_tick(pos, block, SHRIEKING_TICKS); + sim.level_event(3007, pos, 0); + } + /// `SculkSpreader.updateCursors` for a catalyst at `origin`. + pub fn sculk_update_cursors( + &self, + level: &mut L, + ticks: &mut Ticks, + spreader: &mut SculkSpreader, + origin: BlockPos, + spread_veins: bool, + ) { + self.sim(level, ticks) + .sculk_update_cursors(spreader, origin, spread_veins); + } +} diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 6e53a9fa3..5ffd31031 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -923,6 +923,168 @@ fn dripstone_fills_cauldrons() { assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]"); } +#[test] +fn sculk_sensor_phases_and_signal() { + let mut w = world!(); + w.floor(0, 6, "stone"); + let pos = BlockPos::new(0, 1, 0); + let sensor = w.id("sculk_sensor", &[]); + w.set(pos, sensor); + assert!(w.b().sculk_sensor_can_activate(w.get(pos))); + w.f.behaviours + .sculk_sensor_activate(&mut w.level, &mut w.ticks, pos, 11); + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active"); + assert_eq!(w.prop(pos, "power"), "11"); + // The sensor powers the block below it from the top. + let below = BlockPos::new(0, 0, 0); + assert_eq!( + w.f.behaviours + .best_neighbor_signal(&mut w.level, &mut w.ticks, below), + 11, + "the block under an active sensor receives its power" + ); + for _ in 0..29 { + w.tick(); + } + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active"); + w.tick(); + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "cooldown"); + assert_eq!(w.prop(pos, "power"), "0"); + for _ in 0..10 { + w.tick(); + } + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "inactive"); +} + +#[test] +fn calibrated_sensor_is_active_for_ten_ticks() { + let mut w = world!(); + w.floor(0, 6, "stone"); + let pos = BlockPos::new(0, 1, 0); + let sensor = w.id("calibrated_sculk_sensor", &[("facing", "north")]); + w.set(pos, sensor); + w.f.behaviours + .sculk_sensor_activate(&mut w.level, &mut w.ticks, pos, 4); + for _ in 0..9 { + w.tick(); + } + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "active"); + w.tick(); + assert_eq!(w.prop(pos, "sculk_sensor_phase"), "cooldown"); + // The block behind (south) feeds the calibration signal. + let source = w.id("redstone_block", &[]); + w.set(BlockPos::new(0, 1, 1), source); + assert_eq!( + w.f.behaviours + .calibrated_back_signal(&mut w.level, &mut w.ticks, pos), + 15 + ); +} + +#[test] +fn sculk_charge_spreads_veins_and_sculk() { + let mut w = world!(); + w.floor(0, 12, "stone"); + w.floor(-1, 12, "stone"); + let origin = BlockPos::new(0, 1, 0); + let catalyst = w.id("sculk_catalyst", &[]); + w.put(origin, catalyst); + let mut spreader = sculk::SculkSpreader::default(); + spreader.add_cursors(BlockPos::new(2, 1, 0), 40); + assert_eq!(spreader.cursors.len(), 1); + for _ in 0..80 { + w.f.behaviours.sculk_update_cursors( + &mut w.level, + &mut w.ticks, + &mut spreader, + origin, + true, + ); + } + let sculk = w.id("sculk", &[]); + let found = (-12..=12) + .flat_map(|x| (-12..=12).map(move |z| BlockPos::new(x, 0, z))) + .filter(|p| w.get(*p) == sculk) + .count(); + assert!(found > 0, "the charge turned stone into sculk"); + assert!( + w.level + .events + .iter() + .any(|e| matches!(e, LevelEvent::LevelEvent { id: 3006, .. })), + "charge particles are reported" + ); +} + +#[test] +fn shrieker_responds_when_the_shriek_ends() { + let mut w = world!(); + w.floor(0, 6, "stone"); + let pos = BlockPos::new(0, 1, 0); + let shrieker = w.id("sculk_shrieker", &[("can_summon", "true")]); + w.set(pos, shrieker); + w.f.behaviours + .sculk_shrieker_shriek(&mut w.level, &mut w.ticks, pos); + assert_eq!(w.prop(pos, "shrieking"), "true"); + for _ in 0..89 { + w.tick(); + } + assert_eq!(w.prop(pos, "shrieking"), "true"); + w.tick(); + assert_eq!(w.prop(pos, "shrieking"), "false"); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::BlockEvent { + kind: "shrieker_respond", + .. + } + ))); +} + +#[test] +fn catalyst_bloom_lasts_eight_ticks() { + let mut w = world!(); + let pos = BlockPos::new(0, 1, 0); + let catalyst = w.id("sculk_catalyst", &[]); + w.set(pos, catalyst); + w.f.behaviours + .sculk_catalyst_bloom(&mut w.level, &mut w.ticks, pos); + assert_eq!(w.prop(pos, "bloom"), "true"); + for _ in 0..7 { + w.tick(); + } + assert_eq!(w.prop(pos, "bloom"), "true"); + w.tick(); + assert_eq!(w.prop(pos, "bloom"), "false"); +} + +#[test] +fn placing_and_breaking_report_the_affected_state() { + let mut w = world!(); + w.floor(0, 4, "stone"); + let wool = w.id("white_wool", &[]); + let placed = w.place( + "white_wool", + BlockPos::new(0, 0, 0), + Direction::Up, + 0.0, + 0.0, + 0.0, + ); + assert!(matches!(placed, PlaceOutcome::Placed { .. })); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::GameEvent { event: "minecraft:block_place", state: Some(s), .. } if *s == wool + ))); + w.level.events.clear(); + w.f.behaviours + .destroy_block(&mut w.level, &mut w.ticks, BlockPos::new(0, 1, 0), false); + assert!(w.level.events.iter().any(|e| matches!( + e, + LevelEvent::GameEvent { event: "minecraft:block_destroy", state: Some(s), .. } if *s == wool + ))); +} + #[test] fn dispenser_buckets_pick_up_and_empty() { let mut w = world!(); diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index e8eda53cf..719814068 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -151,6 +151,9 @@ impl Sim<'_, L> { Class::RedstoneLamp => self.lamp_tick(pos, state), Class::RedstoneTorch => self.torch_tick(pos, state), Class::Scaffolding => self.scaffolding_tick(pos, state), + Class::SculkSensor => self.sculk_sensor_tick(pos, state), + Class::SculkShrieker => self.sculk_shrieker_tick(pos, state), + Class::SculkCatalyst => self.sculk_catalyst_tick(pos, state), Class::Speleothem => { let tip = b.table.dir(state, p.vertical_direction); if tip == Some(Direction::Up) && !self.can_survive(state, pos) { 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 }