diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6d999c9a8..486b55235 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -58,6 +58,20 @@ pub enum BlockEntity { Beacon(Box), /// `LecternBlockEntity`: the book and the open page. Lectern(Lectern), + /// `CreakingHeartBlockEntity`: its protector and the hurt emitter. + CreakingHeart(Box), +} +/// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`). +#[derive(Clone, Debug, Default)] +pub struct CreakingHeart { + /// The protector: its entity id once resolved, and its UUID (the saved form). + pub creaking: Option<(Option, [i32; 4])>, + pub ticks_existed: i64, + pub ticker: i32, + /// Ticks left of the hurt effect (`emitter`) and where it heads. + pub emitter: i32, + pub emitter_target: Option<[f64; 3]>, + pub output_signal: i32, } #[derive(Clone, Debug, Default)] pub struct Lectern { @@ -101,6 +115,9 @@ impl BlockEntity { speed: 1.0, })); } + if name == "minecraft:creaking_heart" { + return Some(Self::CreakingHeart(Box::default())); + } if name == "minecraft:lectern" { return Some(Self::Lectern(Lectern::default())); } @@ -155,6 +172,7 @@ impl BlockEntity { Self::Jukebox(_) => "minecraft:jukebox", Self::Beacon(_) => "minecraft:beacon", Self::Lectern(_) => "minecraft:lectern", + Self::CreakingHeart(_) => "minecraft:creaking_heart", } } pub fn contents(&self) -> Vec { @@ -164,7 +182,7 @@ impl BlockEntity { Self::Brewing(b) => b.items.iter().flatten().cloned().collect(), Self::Sign(_) => Vec::new(), Self::Jukebox(j) => j.record.iter().cloned().collect(), - Self::Beacon(_) => Vec::new(), + Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), } } @@ -173,7 +191,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &f.items, Self::Brewing(b) => &b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &[], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::CreakingHeart(_) => &[], } } pub fn slots_mut(&mut self) -> &mut [Option] { @@ -181,7 +203,11 @@ impl BlockEntity { Self::Chest(items) => items, Self::Furnace(f) => &mut f.items, Self::Brewing(b) => &mut b.items, - Self::Sign(_) | Self::Jukebox(_) | Self::Beacon(_) | Self::Lectern(_) => &mut [], + Self::Sign(_) + | Self::Jukebox(_) + | Self::Beacon(_) + | Self::Lectern(_) + | Self::CreakingHeart(_) => &mut [], } } } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 02ab14543..bd45054ac 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -246,6 +246,14 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("equipment".into(), Tag::Compound(equipment)); } + "minecraft:creaking" => { + // home_pos: the heart it is bound to. + if let Some(home) = m.extra.home { + map.insert("home_pos".into(), Tag::IntArray(home.to_vec())); + } else { + map.remove(&"home_pos".into()); + } + } "minecraft:villager" => { use crate::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; let data = Tag::compound([ @@ -563,6 +571,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.egg_time = -1 - 400; } } + if m.species() == crate::mobs::Species::Creaking + && let Some(Tag::IntArray(home)) = tag.get("home_pos") + && home.len() == 3 + { + crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]); + } if m.species() == crate::mobs::Species::Wither { m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32; } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cd921c878..6b705f8f1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -13,6 +13,7 @@ mod chat; mod combat; mod commands; mod control; +mod creaking; mod creatures; mod crossbow; mod dispenser; @@ -307,6 +308,17 @@ impl LevelAccess for GameLevel<'_> { 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| { + s.properties + .get("creaking_heart_state") + .is_some_and(|v| v == "uprooted") + }) { + 0 + } else { + signal + }; + } if let Some(signal) = books::lectern_signal(self.world, pos) { return signal; } @@ -613,6 +625,7 @@ struct Game<'a> { hook: Option, tridents: Vec, rockets: Vec, + creaking: creaking::CreakingState, trident_model: Option, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, @@ -1609,6 +1622,7 @@ impl Game<'_> { None } .unwrap_or(self.world.air); + self.creaking_heart_broken(pos); if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) { // Containers.dropContents (shulker boxes keep theirs). let name = facts.name.clone(); @@ -3043,7 +3057,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::CreakingHeart(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -3268,7 +3283,8 @@ impl Game<'_> { BlockEntity::Sign(_) | BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) - | BlockEntity::Lectern(_), + | BlockEntity::Lectern(_) + | BlockEntity::CreakingHeart(_), ) => {} None => { let texture = if self.craft_size == 3 { @@ -4312,6 +4328,7 @@ impl Game<'_> { self.tick_hoppers()?; self.tick_jukeboxes(); self.tick_beacons(); + self.tick_creaking_hearts()?; // ChestLidController: 0.1 per tick towards open/closed. if let Some(key) = self.container { self.chest_open.entry(key).or_insert((0.0, 0.0)); @@ -7671,6 +7688,7 @@ pub fn run() -> Result<()> { hook: None, tridents: Vec::new(), rockets: Vec::new(), + creaking: Default::default(), trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), tnts: Vec::new(), hoppers: HashMap::new(), diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs new file mode 100644 index 000000000..98727ba8b --- /dev/null +++ b/crates/horizon-client/src/game/creaking.rs @@ -0,0 +1,663 @@ +//! The creaking heart block entity (`CreakingHeartBlockEntity`): at night an +//! awake heart in a pale oak trunk spawns a creaking that protects it, +//! hurting the creaking makes the heart emit trails and spread resin over +//! the logs, and breaking the heart tears the creaking down. +use super::Game; +use horizon_client::{ + Result, + containers::{BlockEntity, CreakingHeart}, + mobs::creaking, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{geometry::Aabb, position::BlockPos, random::RandomSource}; +use horizon_world::registry::BlockStateId; +use std::collections::{HashSet, VecDeque}; + +type Pos = (i32, i32, i32); + +/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`. +const ORANGE: u32 = 16_545_810; +const GRAY: u32 = 6_250_335; +/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`. +const TOO_FAR: f64 = 34.0; + +/// `Direction.values()`: down, up, north, south, west, east. +const DIRECTIONS: [[i32; 3]; 6] = [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], +]; +const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; + +/// Comparator input of a heart (`getAnalogOutputSignal`). +pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) -> Option { + match world.block_entities.get(&(pos.x, pos.y, pos.z))? { + BlockEntity::CreakingHeart(h) => Some(h.output_signal), + _ => None, + } +} + +impl Game<'_> { + fn heart_state_name(&self, state: BlockStateId) -> String { + self.res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("creaking_heart_state").cloned()) + .unwrap_or_default() + } + /// `Util.shuffledCopy(Direction.values(), random)`. + fn shuffled_directions(&mut self) -> [usize; 6] { + let mut order = [0, 1, 2, 3, 4, 5]; + for i in (2..=6).rev() { + let j = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize; + order.swap(i - 1, j); + } + order + } + fn is_pale_oak_log(&self, p: Pos) -> bool { + let name = &self.res.facts.get(self.world.block(p.0, p.1, p.2)).name; + self.res + .items + .block_tags + .get("minecraft:pale_oak_logs") + .is_some_and(|s| s.contains(&**name)) + } + fn mob_center(&self, id: u32) -> Option<([f64; 3], Aabb)> { + let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?; + Some((m.center(), m.bounds())) + } + /// The protector's entity, resolving a UUID read from a save. + fn heart_protector(&mut self, heart: &mut CreakingHeart) -> Option { + let (id, uuid) = heart.creaking?; + if let Some(id) = id { + if self.mobs.iter().any(|m| m.id == id && !m.removed) { + return Some(id); + } + // The entity is gone: remember it by UUID until it reappears. + heart.creaking = Some((None, uuid)); + } + if let Some(id) = self.mob_id_for_uuid(uuid) { + heart.creaking = Some((Some(id), uuid)); + return Some(id); + } + if heart.ticks_existed >= 30 { + heart.creaking = None; + } + None + } + /// `CreakingHeartBlockEntity.removeProtector`: the creaking falls apart. + fn heart_remove_protector(&mut self, heart: &mut CreakingHeart, by_player: bool) { + let Some(id) = self.heart_protector(heart) else { + return; + }; + if by_player { + // creakingDeathEffects: a twitching death. + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + creaking::set_tearing_down(m); + m.health = 0.0; + m.death_time = m.death_time.max(0); + let at = m.center(); + self.audio + .play("minecraft:entity.creaking.twitch", Some(at), 1.0, 1.0); + } + } else if let Some(i) = self.mobs.iter().position(|m| m.id == id) { + let mut events = Vec::new(); + creaking::tear_down(&mut self.mobs[i], &mut events); + let _ = self.handle_mob_events(events); + } + heart.creaking = None; + } + fn heart_distance_to_creaking(&self, id: u32, pos: Pos) -> f64 { + self.mob_center(id).map_or(0.0, |_| { + let m = self.mobs.iter().find(|m| m.id == id).unwrap(); + let at = ( + f64::from(pos.0) + 0.5, + f64::from(pos.1), + f64::from(pos.2) + 0.5, + ); + ((m.position.x - at.0).powi(2) + + (m.position.y - at.1).powi(2) + + (m.position.z - at.2).powi(2)) + .sqrt() + }) + } + /// `emitParticles`: trails between the creaking and the heart. + fn heart_emit(&mut self, heart: &mut CreakingHeart, pos: Pos, count: i32, towards: bool) { + let Some(id) = self.heart_protector(heart) else { + return; + }; + let Some((_, b)) = self.mob_center(id) else { + return; + }; + let (lo, hi) = (b.min_position(), b.max_position()); + for _ in 0..count { + let r = &mut self.world.random; + let mut source = [ + lo.x + r.next_double() * (hi.x - lo.x), + lo.y + r.next_double() * (hi.y - lo.y), + lo.z + r.next_double() * (hi.z - lo.z), + ]; + let mut destination = [ + f64::from(pos.0) + r.next_double(), + f64::from(pos.1) + r.next_double(), + f64::from(pos.2) + r.next_double(), + ]; + if towards { + std::mem::swap(&mut source, &mut destination); + } + let duration = r.next_int_bound(40).unwrap_or(0) + 10; + let color = if towards { ORANGE } else { GRAY }; + self.particles.add( + &ParticleOptions::trail(destination, color, duration), + source, + [0.0; 3], + ); + } + } + /// `CreakingHeartBlockEntity.spreadResin`: a resin clump on the first log + /// face found within two steps of pale oak logs. + fn heart_spread_resin(&mut self, pos: Pos) -> Option { + let mut visited: HashSet = HashSet::new(); + let mut queue: VecDeque<(Pos, i32)> = VecDeque::new(); + queue.push_back((pos, 0)); + let mut count = 0; + while let Some((current, depth)) = queue.pop_front() { + if !visited.insert(current) { + continue; + } + // The node processor. + if self.is_pale_oak_log(current) { + for d in self.shuffled_directions() { + let n = ( + current.0 + DIRECTIONS[d][0], + current.1 + DIRECTIONS[d][1], + current.2 + DIRECTIONS[d][2], + ); + let neighbour = self.world.block(n.0, n.1, n.2); + let opposite = d ^ 1; + let clump = self.resin_clump_for(neighbour); + let Some(clump) = clump else { continue }; + if self.prop_is(clump, FACE_NAMES[opposite]) { + continue; + } + let Some(placed) = self.with_face(clump, FACE_NAMES[opposite]) else { + continue; + }; + let _ = self.level_set([n.0, n.1, n.2], placed); + return Some(n); + } + } + count += 1; + if count >= 64 { + return None; + } + if depth < 2 { + // The neighbour provider: adjacent pale oak logs. + for d in self.shuffled_directions() { + let n = ( + current.0 + DIRECTIONS[d][0], + current.1 + DIRECTIONS[d][1], + current.2 + DIRECTIONS[d][2], + ); + if self.is_pale_oak_log(n) { + queue.push_back((n, depth + 1)); + } + } + } + } + None + } + /// The state a face of resin can be added to: air, a source of water, or + /// a clump already there. + fn resin_clump_for(&self, neighbour: BlockStateId) -> Option { + let registry = self.res.assets.registry; + let clump = registry.default_state("minecraft:resin_clump")?; + let facts = self.res.facts.get(neighbour); + if self.res.facts.is_air(neighbour) { + Some(clump) + } else if &*facts.name == "minecraft:water" + && facts.fluid_level == 8 + && !facts.fluid_falling + { + let mut s = registry.state(clump)?.clone(); + s.properties.insert("waterlogged".into(), "true".into()); + registry.resolve(&s).ok() + } else if &*facts.name == "minecraft:resin_clump" { + Some(neighbour) + } else { + None + } + } + fn prop_is(&self, state: BlockStateId, key: &str) -> bool { + self.res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get(key)) + .is_some_and(|v| v == "true") + } + fn with_face(&self, state: BlockStateId, face: &str) -> Option { + let mut s = self.res.assets.registry.state(state)?.clone(); + s.properties.insert(face.to_owned(), "true".to_owned()); + self.res.assets.registry.resolve(&s).ok() + } + /// A creaking bound to the heart at `home` was hurt (`creakingHurt`). + pub(super) fn creaking_hurt(&mut self, home: [i32; 3], id: u32, by_player: bool) { + if !by_player { + return; + } + let key = (home[0], home[1], home[2]); + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key) + else { + return; + }; + if self.heart_protector(&mut heart) == Some(id) && heart.emitter <= 0 { + self.heart_emit(&mut heart, key, 20, false); + let state = self.world.block(key.0, key.1, key.2); + if self.heart_state_name(state) == "awake" { + let clumps = 2 + self.world.random.next_int_bound(2).unwrap_or(0); + for _ in 0..clumps { + if let Some(at) = self.heart_spread_resin(key) { + self.audio.play( + "minecraft:block.resin.place", + Some([ + f64::from(at.0) + 0.5, + f64::from(at.1) + 0.5, + f64::from(at.2) + 0.5, + ]), + 1.0, + 1.0, + ); + } + } + } + heart.emitter = 100; + heart.emitter_target = self.mob_center(id).map(|(c, _)| c); + } + self.world + .block_entities + .insert(key, BlockEntity::CreakingHeart(heart)); + } + /// `Creaking.tearDown`: the crumble particles. + pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) { + let registry = self.res.assets.registry; + let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| { + let Some(mut state) = registry + .default_state(name) + .and_then(|s| registry.state(s).cloned()) + else { + return; + }; + for (k, v) in props { + state.properties.insert((*k).to_owned(), (*v).to_owned()); + } + let Ok(id) = registry.resolve(&state) else { + return; + }; + let Some((sprite, tint)) = this.particle_sprite(id) else { + return; + }; + for _ in 0..count { + let r = &mut this.world.random; + let p = [ + center[0] + r.next_gaussian() * spread[0], + center[1] + r.next_gaussian() * spread[1], + center[2] + r.next_gaussian() * spread[2], + ]; + this.particles.add( + &ParticleOptions::block(ParticleType::BlockCrumble, sprite.clone(), tint), + p, + [0.0; 3], + ); + } + }; + crumble(self, "minecraft:pale_oak_wood", &[], 100); + crumble( + self, + "minecraft:creaking_heart", + &[("creaking_heart_state", "awake")], + 10, + ); + } + /// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to + /// death and a natural heart drops experience. + pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) { + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key) + else { + return; + }; + self.heart_remove_protector(&mut heart, true); + let state = self.world.block(key.0, key.1, key.2); + if self.prop_is(state, "natural") && !self.creative && !self.spectator() { + let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32; + self.spawn_orbs( + [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ], + xp, + ); + } + self.world + .block_entities + .insert(key, BlockEntity::CreakingHeart(heart)); + } + /// `SpawnUtil.trySpawnMob(CREAKING, .., 5, 16, 8, ON_TOP_OF_COLLIDER_NO_LEAVES, true)`. + fn spawn_protector(&mut self, pos: Pos) -> Option { + let t = self.res.mob_types.get("minecraft:creaking").cloned()?; + for _ in 0..5 { + let r = &mut self.world.random; + let dx = r.next_int_bound(33).unwrap_or(16) - 16; + let dz = r.next_int_bound(33).unwrap_or(16) - 16; + let mut at = (pos.0 + dx, pos.1 + 8, pos.2 + dz); + if !self.world.loaded(at.0, at.2) { + continue; + } + // moveToPossibleSpawnPosition: scan down for a collider with room above. + let mut above = self.world.block(at.0, at.1, at.2); + let mut found = false; + for _ in 0..=16 { + at.1 -= 1; + let current = self.world.block(at.0, at.1, at.2); + let facts = self.res.facts.get(current); + let leaves = self + .res + .items + .block_tags + .get("minecraft:leaves") + .is_some_and(|s| s.contains(&*facts.name)); + let clear_above = self + .res + .behaviours + .collision_shape(above) + .map_or(!self.res.facts.get(above).full_collision, |s| s.is_empty()); + if clear_above && !leaves && facts.sturdy_full & (1 << 1) != 0 { + at.1 += 1; + found = true; + break; + } + above = current; + } + if !found { + continue; + } + // noCollision(spawn box) and no liquid. + let w = t.width / 2.0; + let bounds = Aabb::new( + horizon_core::geometry::Vec3::new( + f64::from(at.0) + 0.5 - w, + f64::from(at.1), + f64::from(at.2) + 0.5 - w, + ), + horizon_core::geometry::Vec3::new( + f64::from(at.0) + 0.5 + w, + f64::from(at.1) + t.height, + f64::from(at.2) + 0.5 + w, + ), + ); + let mut scene = horizon_client::collisions::SceneCollisions { + world: &self.world, + binding: self.collision, + }; + let free = scene.unobstructed(bounds).unwrap_or(false); + let wet = self.res.facts.get(self.world.block(at.0, at.1, at.2)).fluid + != horizon_client::blocks::Fluid::None; + if !free || wet { + continue; + } + let id = self.spawn_mob( + "minecraft:creaking", + [ + f64::from(at.0) + 0.5, + f64::from(at.1), + f64::from(at.2) + 0.5, + ], + false, + )?; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + creaking::set_transient(m, [pos.0, pos.1, pos.2]); + } + return Some(id); + } + None + } + /// `CreakingHeartBlockEntity.computeAnalogOutputSignal`. + fn heart_output(&mut self, heart: &mut CreakingHeart, pos: Pos) -> i32 { + if heart.creaking.is_none() { + return 0; + } + let Some(id) = self.heart_protector(heart) else { + return 0; + }; + let distance = self.heart_distance_to_creaking(id, pos).clamp(0.0, 32.0) / 32.0; + 15 - (distance * 15.0).floor() as i32 + } + /// `CreakingHeartBlockEntity.serverTick` for every heart. + pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> { + let keys: Vec = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_))) + .map(|(k, _)| *k) + .collect(); + for key in keys { + let Some(BlockEntity::CreakingHeart(mut heart)) = + self.world.block_entities.remove(&key) + else { + continue; + }; + let state = self.world.block(key.0, key.1, key.2); + if &*self.res.facts.get(state).name != "minecraft:creaking_heart" { + // The block is gone: preRemoveSideEffects. + self.heart_remove_protector(&mut heart, false); + continue; + } + if self.heart_state_name(state) != "uprooted" { + self.heart_tick(&mut heart, key, state)?; + } + self.world + .block_entities + .insert(key, BlockEntity::CreakingHeart(heart)); + } + self.scan_for_hearts(); + Ok(()) + } + fn heart_tick( + &mut self, + heart: &mut CreakingHeart, + key: Pos, + state: BlockStateId, + ) -> Result<()> { + heart.ticks_existed += 1; + let output = self.heart_output(heart, key); + if output != heart.output_signal { + heart.output_signal = output; + self.container_changed(key); + } + if heart.emitter > 0 { + if heart.emitter > 50 { + self.heart_emit(heart, key, 1, true); + self.heart_emit(heart, key, 1, false); + } + if heart.emitter % 10 == 0 && heart.emitter_target.is_some() { + if let Some(id) = self.heart_protector(heart) + && let Some((c, _)) = self.mob_center(id) + { + heart.emitter_target = Some(c); + } + if let Some(target) = heart.emitter_target { + let center = [ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]; + let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0; + let at = [ + (center[0] - target[0]) * progress + target[0], + (center[1] - target[1]) * progress + target[1], + (center[2] - target[2]) * progress + target[2], + ]; + let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5; + self.audio + .play("minecraft:block.creaking_heart.hurt", Some(at), volume, 1.0); + } + } + heart.emitter -= 1; + } + let ticker = heart.ticker; + heart.ticker -= 1; + if ticker >= 0 { + return Ok(()); + } + heart.ticker = self.world.random.next_int_bound(5).unwrap_or(0) + 20; + // updateCreakingState: logs gone and no creaking means uprooted. + let active = self.creaking_active(); + let has_logs = self.with_level(|b, level, ticks| { + b.creaking_heart_has_logs(level, ticks, BlockPos::new(key.0, key.1, key.2), state) + }); + let wanted = if !has_logs && heart.creaking.is_none() { + "uprooted" + } else if active { + "awake" + } else { + "dormant" + }; + let mut current = self.heart_state_name(state); + if wanted != current + && let Some(next) = self.heart_with_state(state, wanted) + { + self.level_set([key.0, key.1, key.2], next)?; + current = wanted.to_owned(); + if wanted == "uprooted" { + return Ok(()); + } + } + if heart.creaking.is_none() { + if current == "awake" && self.spawning_monsters() { + let near = self.player.as_ref().is_some_and(|p| { + let (dx, dy, dz) = ( + p.position.x - (f64::from(key.0) + 0.5), + p.position.y - (f64::from(key.1) + 0.5), + p.position.z - (f64::from(key.2) + 0.5), + ); + dx * dx + dy * dy + dz * dz < 32.0 * 32.0 + }) && !self.spectator(); + if near && let Some(id) = self.spawn_protector(key) { + let uuid = self.uuid_for(id); + heart.creaking = Some((Some(id), uuid)); + heart.ticks_existed = 0; + let at = self.mob_center(id).map(|(c, _)| c); + self.audio + .play("minecraft:entity.creaking.spawn", at, 1.0, 1.0); + self.audio.play( + "minecraft:block.creaking_heart.spawn", + Some([ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]), + 1.0, + 1.0, + ); + } + } + } else if let Some(id) = self.heart_protector(heart) { + let persistent = self + .mobs + .iter() + .find(|m| m.id == id) + .is_some_and(|m| m.persistent); + let eye = self.player_view().map(|v| v.eye); + let stuck = self + .mobs + .iter_mut() + .find(|m| m.id == id) + .is_some_and(|m| creaking::player_is_stuck(m, eye)); + if (!active && !persistent) + || self.heart_distance_to_creaking(id, key) > TOO_FAR + || stuck + { + self.heart_remove_protector(heart, false); + } + } + Ok(()) + } + fn heart_with_state(&self, state: BlockStateId, wanted: &str) -> Option { + let mut s = self.res.assets.registry.state(state)?.clone(); + s.properties + .insert("creaking_heart_state".to_owned(), wanted.to_owned()); + self.res.assets.registry.resolve(&s).ok() + } + /// `ServerLevel.isSpawningMonsters`. + fn spawning_monsters(&self) -> bool { + self.ui.difficulty != 0 && self.ui.rules.bool("spawn_monsters") + } + /// `EnvironmentAttributes.CREAKING_ACTIVE`. + pub(super) fn creaking_active(&mut self) -> bool { + self.with_level(|b, level, ticks| b.creaking_active(level, ticks)) + } + /// Hearts that came with generated or loaded chunks get their block + /// entity (`newBlockEntity`) the first time their chunk is seen. + fn scan_for_hearts(&mut self) { + let Some(heart) = self + .res + .assets + .registry + .default_state("minecraft:creaking_heart") + else { + return; + }; + let keys: Vec<(i32, i32)> = self + .world + .chunks + .iter() + .filter(|(k, c)| c.lit && !self.creaking.scanned.contains(k)) + .map(|(k, _)| *k) + .collect(); + for key in keys { + self.creaking.scanned.insert(key); + let Some(chunk) = self.world.chunks.get(&key).cloned() else { + continue; + }; + let name = |id: u16| &*self.res.facts.get(BlockStateId(u32::from(id))).name; + let _ = heart; + for (si, section) in chunk.sections.iter().enumerate() { + if section.is_uniform(0) { + continue; + } + for i in 0..4096 { + let id = section.get(i); + if name(id) != "minecraft:creaking_heart" { + continue; + } + let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32); + let pos = ( + key.0 * 16 + lx, + horizon_client::chunk::MIN_Y + si as i32 * 16 + ly, + key.1 * 16 + lz, + ); + self.world + .block_entities + .entry(pos) + .or_insert_with(|| BlockEntity::CreakingHeart(Box::default())); + } + } + } + let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); + self.creaking.scanned.retain(|k| loaded.contains(k)); + } +} + +/// What the creaking code remembers between ticks. +#[derive(Default)] +pub(super) struct CreakingState { + /// Chunks already scanned for heart blocks. + scanned: HashSet<(i32, i32)>, +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f2cbf245e..7f13adffc 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -970,6 +970,14 @@ impl Game<'_> { } }, MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::CreakingHurt { + home, + by_player, + id, + } => self.creaking_hurt(home, id, by_player), + MobEvent::CreakingTearDown { center, spread } => { + self.creaking_tear_down(center, spread) + } MobEvent::GiftLoot { table, at } => { let drops = self.res diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 548ae34ee..46e934092 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -269,9 +269,17 @@ impl Game<'_> { } self.persist.raw.insert(id, tag); } - fn uuid_for(&mut self, id: u32) -> [i32; 4] { + pub(super) fn uuid_for(&mut self, id: u32) -> [i32; 4] { *self.persist.uuids.entry(id).or_insert_with(random_uuid) } + /// The loaded mob with a saved UUID. + pub(super) fn mob_id_for_uuid(&self, uuid: [i32; 4]) -> Option { + self.persist + .uuids + .iter() + .find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id && !m.removed)) + .map(|(id, _)| *id) + } /// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`). fn state_from_nbt(&self, tag: &Tag) -> Option { let registry = self.res.assets.registry; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 24dafbf94..f53eb3901 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -11,6 +11,7 @@ pub mod anim; pub mod aquatic; pub mod camel; pub mod control; +pub mod creaking; pub mod cube; pub mod data; pub mod enderman; @@ -664,6 +665,17 @@ pub enum MobEvent { table: &'static str, at: [f64; 3], }, + /// A creaking bound to the heart at `home` was hurt (`creakingHurt` when a player did it). + CreakingHurt { + home: [i32; 3], + by_player: bool, + id: u32, + }, + /// `Creaking.tearDown`: crumbling particles around the creaking. + CreakingTearDown { + center: [f64; 3], + spread: [f64; 3], + }, } /// How a spawned-by-kind mob should be set up. #[derive(Clone, Debug, Default)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index d7a9e0084..a0ae29a97 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, + Creaking, } pub fn family(s: Species) -> Family { use Species as S; @@ -121,6 +122,7 @@ pub fn family(s: Species) -> Family { S::Ravager => Family::Ravager, S::Wither => Family::Wither, S::Allay => Family::Allay, + S::Creaking => Family::Creaking, S::Villager => Family::Villager, S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin, S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse | S::Camel => { @@ -169,6 +171,7 @@ pub fn register(m: &mut Mob) { Family::Wither => super::wither::register(m), Family::Allay => super::allay::register(m), Family::Villager => super::villager::register(m), + Family::Creaking => super::creaking::register(m), } } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). @@ -251,7 +254,11 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { return false; } base_tick(m, w, events); - if m.death_time >= 20 { + if m.death_time >= super::creaking::death_limit(m) { + // Creaking.tickDeath: a heart's creaking crumbles away. + if super::creaking::is_creaking(m) && super::creaking::tearing_down(m) { + super::creaking::tear_down(m, events); + } return false; } ai_step(m, w, events); @@ -391,6 +398,8 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Axolotl if !m.fluids.in_water => "entity.axolotl.idle_air", Species::Bat if m.extra.flag && m.random.next_int_bound(4).unwrap_or(1) != 0 => return, Species::Allay if m.extra.main_hand.is_some() => "entity.allay.ambient_with_item", + // Creaking.getAmbientSound: silent while awake. + Species::Creaking if m.extra.flag => return, // Shulker.playAmbientSound: silent while closed. Species::Shulker if m.extra.counter == 0 => return, Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry", @@ -405,6 +414,9 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } /// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions). fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if super::creaking::is_creaking(m) { + super::creaking::update(m, w, events); + } if m.ai.no_jump_delay > 0 { m.ai.no_jump_delay -= 1; } @@ -486,6 +498,10 @@ fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool { /// Mob.serverAiStep fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.ai.no_action_time += 1; + // A creaking looked at stands still. + if super::creaking::is_creaking(m) && !super::creaking::can_move(m) { + return; + } // A saddled mount follows its rider instead of its goals. if super::equine::controlled(m) { super::equine::ridden_step(m); @@ -664,6 +680,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { match m.species() { // Allay.hurtServer: its liked player cannot hurt it. 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::Shulker => super::shulker::accepts(m, source), Species::Enderman => super::enderman::on_damage(m, source), @@ -707,6 +724,9 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if m.species() == Species::Ravager { super::ravager::on_attack(m, cx.events); } + if super::creaking::is_creaking(m) { + super::creaking::on_attack(m, cx.events); + } let mut amount = m.attrs.attack_damage; let from = [m.position.x, m.position.y, m.position.z]; let source = Damage::mob(m.id, from); diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index f56e504a4..ae44a2630 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -9,6 +9,7 @@ use std::f32::consts::PI; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Anim { Allay, + Creaking, Camel, Wither, Vex, @@ -346,6 +347,7 @@ pub fn setup( match m.kind.anim { Anim::Camel => super::camel::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 => { super::aquatic::anim(m, s, p) } diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs new file mode 100644 index 000000000..0a2e8603a --- /dev/null +++ b/crates/horizon-client/src/mobs/creaking.rs @@ -0,0 +1,365 @@ +//! Creakings (`Creaking`, `CreakingAi`): they freeze while any player looks at +//! them, wake up when one looks from within 12 blocks, then hunt the nearest +//! visible player and hit every 40 ticks. One bound to a creaking heart takes +//! no damage (it only sways and hurts the heart's resin spreader), dies when +//! the heart no longer protects it and falls apart with the heart. +use super::{ + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, + anim::{Poses, State}, + goals::{Cx, Float, Goal, LookAtPlayer, MeleeAttack, Stroll, TARGET, goal_clone}, + keyframes::Animation, + path::PathType, +}; +use crate::containers::BlockEntity; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use std::collections::HashMap; + +/// `Extra.ints` slots. +const INVULNERABLE: usize = 0; +const ATTACKING: usize = 1; +const STUCK: usize = 2; +const TEARING_DOWN: usize = 3; +const EYES: usize = 4; +const NEXT_FLICKER: usize = 5; +/// `Extra.counter` bits: hurt while protected, and by a player. +const HURT: i32 = 1; +const HURT_BY_PLAYER: i32 = 2; + +/// `Creaking.ACTIVATION_RANGE_SQ`. +const ACTIVATION_RANGE_SQ: f64 = 144.0; +/// `Creaking.INVULNERABILITY_ANIMATION_DURATION` and the attack animation. +const INVULNERABILITY_TICKS: i32 = 8; +const ATTACK_TICKS: i32 = 15; +/// `Creaking.TWITCH_DEATH_DURATION`. +const TWITCH_TICKS: i32 = 45; + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(2, MeleeAttack::new(1.0, false).interval(40)); + g.add(5, Stroll::avoiding_water(0.3)); + g.add(6, LookAtPlayer::new(8.0)); + m.ai.targets.add(1, HuntPlayer); +} +/// Bound to a heart (`getHomePos() != null`). +pub fn heart_bound(m: &Mob) -> bool { + is_creaking(m) && m.extra.home.is_some() +} +pub fn tearing_down(m: &Mob) -> bool { + is_creaking(m) && m.extra.ints[TEARING_DOWN] != 0 +} +/// `Creaking.canMove`: false while a player looks at it. +pub fn can_move(m: &Mob) -> bool { + !m.extra.flag2 +} +/// `Creaking.isActive`. +pub fn is_active(m: &Mob) -> bool { + m.extra.flag +} +/// `Creaking.setTransient`: bind to the heart at `pos` and avoid damage. +pub fn set_transient(m: &mut Mob, pos: [i32; 3]) { + m.extra.home = Some(pos); + 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); +} +/// `Creaking.setTearingDown`: the heart was broken by someone. +pub fn set_tearing_down(m: &mut Mob) { + m.extra.ints[TEARING_DOWN] = 1; +} +/// `Creaking.hasGlowingEyes` / `isActive`: the eyes layer shows. +pub fn eyes_glowing(m: &Mob) -> bool { + if tearing_down(m) { + m.extra.ints[EYES] != 0 + } else { + is_active(m) + } +} +/// Ticks of death animation before the mob is removed (`tickDeath`). +pub fn death_limit(m: &Mob) -> i32 { + if heart_bound(m) && tearing_down(m) { + TWITCH_TICKS + 1 + } else { + 20 + } +} +/// `Creaking.tearDown`: crumbles away. +pub fn tear_down(m: &mut Mob, events: &mut Vec) { + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + events.push(MobEvent::CreakingTearDown { + center: [ + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ], + spread: [ + (hi.x - lo.x) * 0.3, + (hi.y - lo.y) * 0.3, + (hi.z - lo.z) * 0.3, + ], + }); + m.voice("entity.creaking.death", events); + m.removed = true; +} +/// `Creaking.hurtServer` for a heart-bound creaking: no damage, only the +/// invulnerability animation and the heart's reaction. Returns whether the +/// normal damage path should run. +pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool { + if !heart_bound(m) || source.kind == DamageKind::Generic { + return true; + } + if source.is_fire() || !m.alive() || m.extra.ints[INVULNERABLE] > 0 { + return false; + } + let by_player = source.attacker == Some(Who::Player); + // The direct entity must be living or a projectile (or a player must be to blame). + let direct = matches!( + source.kind, + DamageKind::PlayerAttack + | DamageKind::MobAttack + | DamageKind::Arrow + | DamageKind::Thrown + | DamageKind::Fireball + | DamageKind::Thorns + ); + if !direct && !by_player { + return false; + } + m.extra.ints[INVULNERABLE] = INVULNERABILITY_TICKS; + m.extra.counter |= HURT | if by_player { HURT_BY_PLAYER } else { 0 }; + false +} +/// `Creaking.doHurtTarget` extras: the attack animation and sound. +pub fn on_attack(m: &mut Mob, events: &mut Vec) { + m.extra.ints[ATTACKING] = ATTACK_TICKS; + m.voice("entity.creaking.attack", events); +} +/// The heart this creaking is bound to protects it (`isProtector`); a link +/// read from a save is trusted until the heart resolves it. +fn protected(m: &Mob, w: &MobWorld) -> bool { + let Some(home) = m.extra.home else { + return true; + }; + match w.world.block_entities.get(&(home[0], home[1], home[2])) { + Some(BlockEntity::CreakingHeart(h)) => match h.creaking { + Some((Some(id), _)) => id == m.id, + Some((None, _)) => true, + None => false, + }, + _ => false, + } +} +/// `Creaking.tick` and the start of `aiStep`: protection, timers, freezing. +pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + // Creaking.tick: without its heart's protection it dies. + if heart_bound(m) && m.alive() && !protected(m, w) { + m.health = 0.0; + } + for slot in [INVULNERABLE, ATTACKING] { + if m.extra.ints[slot] > 0 { + m.extra.ints[slot] -= 1; + } + } + let age = m.age as f32; + m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age); + m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age); + m.anim.states[2].animate_when(tearing_down(m), age); + if m.extra.counter & HURT != 0 { + // hurtServer: sway, and the heart reacts to a player's hit. + if protected(m, w) { + let by_player = m.extra.counter & HURT_BY_PLAYER != 0; + if let Some(home) = m.extra.home { + events.push(MobEvent::CreakingHurt { + home, + by_player, + id: m.id, + }); + } + m.voice("entity.creaking.sway", events); + } + m.extra.counter &= !(HURT | HURT_BY_PLAYER); + } + // checkEyeBlink: the eyes of a creaking falling apart flicker. + if m.death_time > m.extra.ints[NEXT_FLICKER] { + let glowing = m.extra.ints[EYES] != 0; + let (lo, hi) = if glowing { + (2, 8) + } else { + (m.death_time / 4, m.death_time / 2) + }; + let span = (hi - lo + 1).max(1); + m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0); + m.extra.ints[EYES] = i32::from(!glowing); + } + if !m.alive() { + return; + } + let now = check_can_move(m, w, events); + if now != can_move(m) { + if now { + m.voice("entity.creaking.unfreeze", events); + } else { + stop_in_place(m); + m.voice("entity.creaking.freeze", events); + } + m.extra.flag2 = !now; + } +} +/// `Mob.stopInPlace`. +pub fn stop_in_place(m: &mut Mob) { + m.nav_stop(); + m.ai.xxa = 0.0; + m.ai.yya = 0.0; + m.ai.zza = 0.0; + m.ai.speed = 0.0; +} +fn activate(m: &mut Mob, events: &mut Vec) { + m.ai.target = Some(Who::Player); + m.voice("entity.creaking.activate", events); + m.extra.flag = true; +} +fn deactivate(m: &mut Mob, events: &mut Vec) { + m.ai.target = None; + m.voice("entity.creaking.deactivate", events); + m.extra.flag = false; +} +/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5, mid)`. +fn looked_at_by(m: &Mob, w: &MobWorld) -> bool { + let Some(p) = &w.player else { return false }; + let look = p.look; + let eye = m.eye_y(); + [eye, m.position.y + 0.5, (eye + m.position.y) / 2.0] + .into_iter() + .any(|y| { + let d = [ + m.position.x - p.position.x, + y - p.eye[1], + m.position.z - p.position.z, + ]; + let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + if len < 1.0e-6 { + return true; + } + let dot = (look[0] * d[0] + look[1] * d[1] + look[2] * d[2]) / len; + dot > 0.5 + && w.line_of_sight( + Vec3::new(p.eye[0], p.eye[1], p.eye[2]), + Vec3::new(m.position.x, y, m.position.z), + ) + }) +} +/// `Creaking.checkCanMove`: false while looked at; also wakes and calms it. +fn check_can_move(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { + let active = is_active(m); + // NEAREST_PLAYERS: players within the follow range. + let near = w.player.as_ref().filter(|p| { + let d = Vec3::new(p.position.x, p.position.y, p.position.z); + m.distance_sqr(d) < 32.0 * 32.0 + }); + let Some(p) = near else { + if active { + deactivate(m, events); + } + return true; + }; + // canAttack: alive and not creative or spectator. + let attackable = p.alive && !p.creative; + if attackable { + // GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake. + let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin"); + if (!active || !disguised) && looked_at_by(m, w) { + if active { + return false; + } + if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ { + activate(m, events); + return false; + } + } + } else if active { + deactivate(m, events); + } + true +} +/// `Creaking.playerIsStuckInYou`: the player's eyes inside it for more than 4 ticks. +pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool { + let Some(eye) = eye else { + m.extra.ints[STUCK] = 0; + return false; + }; + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + let inside = eye[0] >= lo.x + && eye[0] <= hi.x + && eye[1] >= lo.y + && eye[1] <= hi.y + && eye[2] >= lo.z + && eye[2] <= hi.z; + if inside { + m.extra.ints[STUCK] += 1; + m.extra.ints[STUCK] > 4 + } else { + m.extra.ints[STUCK] = 0; + false + } +} +/// The nearest attackable player the creaking can see. +fn sees_attackable_player(m: &mut Mob, cx: &mut Cx) -> bool { + let Some(p) = &cx.w.player else { + return false; + }; + let near = m.distance_sqr(p.position) < m.attrs.follow_range.powi(2); + p.alive && !p.creative && near && m.sees(cx.w, Who::Player) +} +/// `StartAttacking` / `StopAttackingIfTargetInvalid`: while awake, hunt the +/// nearest visible player. +#[derive(Clone, Debug)] +struct HuntPlayer; +impl Goal for HuntPlayer { + goal_clone!(); + fn flags(&self) -> u8 { + TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !is_active(m) || !sees_attackable_player(m, cx) { + return false; + } + m.ai.target = Some(Who::Player); + true + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + is_active(m) && m.ai.target == Some(Who::Player) && sees_attackable_player(m, cx) + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + if m.ai.target == Some(Who::Player) { + m.ai.target = None; + } + } +} +/// `CreakingModel.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()); + let get = |n: &str| animations.get(&format!("CreakingAnimation.CREAKING_{n}")); + if can_move(m) + && let Some(walk) = get("WALK") + { + walk.apply_walk(s.pos, s.speed, 1.0, 1.0, p); + } + for (state, name) in [ + (&m.anim.states[0], "ATTACK"), + (&m.anim.states[1], "INVULNERABLE"), + (&m.anim.states[2], "DEATH"), + ] { + if let (Some(ms), Some(a)) = (state.millis(s.age), get(name)) { + a.apply(ms, 1.0, p); + } + } +} +/// The creaking species exists in the species table. +pub fn is_creaking(m: &Mob) -> bool { + m.species() == Species::Creaking +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 814d6a3f1..b47cc30d6 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -731,6 +731,8 @@ pub struct MeleeAttack { pub until_attack: i32, last_check: i64, raise_arm: i32, + /// Ticks between attacks (20 unless set). + pub interval: i32, } impl MeleeAttack { pub fn new(speed: f64, follow_unseen: bool) -> Self { @@ -743,12 +745,17 @@ impl MeleeAttack { until_attack: 0, last_check: i64::MIN / 2, raise_arm: 0, + interval: 20, } } pub fn zombie(mut self) -> Self { self.zombie = true; self } + pub fn interval(mut self, ticks: i32) -> Self { + self.interval = ticks; + self + } } impl Goal for MeleeAttack { goal_clone!(); @@ -834,7 +841,7 @@ impl Goal for MeleeAttack { } self.until_attack = (self.until_attack - 1).max(0); if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) { - self.until_attack = adjusted(true, 20); + self.until_attack = adjusted(true, self.interval); m.swing(); super::ai::do_hurt_target(m, who, cx); } diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 327b0662b..00ebfb71a 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -437,7 +437,12 @@ impl Mob { let distance = (dx * dx + dy * dy + dz * dz).sqrt() as f32; self.previous_limb_speed = self.limb_speed; if self.alive() { - let target = (distance * 4.0).min(1.0); + // Creaking.updateWalkAnimation walks the model faster. + let target = if self.species() == super::Species::Creaking { + (distance * 25.0).min(3.0) + } else { + (distance * 4.0).min(1.0) + }; self.limb_speed += (target - self.limb_speed) * 0.4; self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 }; } else { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 13a24e1a9..d640b6973 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -403,6 +403,13 @@ pub fn layers(m: &Mob) -> Vec { ); } } + S::Creaking if super::creaking::eyes_glowing(m) => push( + &mut v, + "creaking#eyes", + "entity/creaking/creaking_eyes", + white, + true, + ), S::Spider | S::CaveSpider => push( &mut v, &m.kind.model_key(), @@ -622,7 +629,7 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { .unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())), }; let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation; - if m.death_time > 0 { + if m.death_time > 0 && !super::creaking::tearing_down(m) { let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) .sqrt() .min(1.0); @@ -740,7 +747,8 @@ pub fn render_with( out: &mut Vec, ) { let base = base_transform(m, alpha, camera); - let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0); + let overlay = + u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))); let s = anim::state(m, alpha); let (model_key, texture) = body(m); let model = m @@ -793,7 +801,8 @@ pub fn render_single( out: &mut Vec, ) { let base = base_transform(m, alpha, camera); - let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0); + let overlay = + u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))); let s = anim::state(m, alpha); let model = m.kind.model.clone(); let mut poses = Poses::new(&model); diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index 820006f32..1d38d4789 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, + Creaking, } /// Baby bounding boxes (each class's BABY_DIMENSIONS). #[derive(Clone, Copy, Debug)] @@ -914,6 +915,20 @@ pub const ALL: &[Def] = &[ None, Baby::None ), + def!( + Creaking, + "creaking", + "creaking#main", + "entity/creaking/creaking", + A::Creaking, + [ + "entity.creaking.ambient", + "entity.generic.hurt", + "entity.creaking.death" + ], + Some("entity.creaking.step"), + Baby::None + ), def!( Camel, "camel", diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 8fa53a860..5e075d29e 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -41,6 +41,7 @@ macro_rules! particle_types { particle_types! { Block = "block", BlockCrumble = "block_crumble", + Trail = "trail", DustPillar = "dust_pillar", FallingDust = "falling_dust", Smoke = "smoke", @@ -140,6 +141,8 @@ pub struct ParticleOptions { pub color: [f32; 4], /// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`. pub scale: f32, + /// `TrailParticleOption`: the point it flies to and how many ticks it takes. + pub trail: Option<([f64; 3], i32)>, } impl ParticleOptions { pub fn simple(ty: ParticleType) -> Self { @@ -148,6 +151,20 @@ impl ParticleOptions { block: None, color: [1.0; 4], scale: 1.0, + trail: None, + } + } + /// `TrailParticleOption(target, color, duration)`. + pub fn trail(target: [f64; 3], rgb: u32, duration: i32) -> Self { + Self { + color: [ + ((rgb >> 16) & 255) as f32 / 255.0, + ((rgb >> 8) & 255) as f32 / 255.0, + (rgb & 255) as f32 / 255.0, + 1.0, + ], + trail: Some((target, duration)), + ..Self::simple(ParticleType::Trail) } } pub fn block(ty: ParticleType, sprite: String, tint: u32) -> Self { @@ -261,6 +278,10 @@ enum Behaviour { DragonBreath { hit_ground: bool, }, + /// `TrailParticle`: eases towards its target over its lifetime. + Trail { + target: [f64; 3], + }, } #[derive(Clone, Copy, Debug, PartialEq)] enum DripStage { @@ -1662,6 +1683,24 @@ impl ParticleEngine { q.set_power(o.scale); q } + T::Trail => { + let (target, duration) = o.trail?; + let mut q = Particle::at(r, ty, p); + let jitter = |r: &mut LegacyRandom| 0.875 + r.next_float() * 0.25; + let (jr, jg, jb) = (jitter(r), jitter(r), jitter(r)); + q.set_color( + (o.color[0] * jr).min(1.0), + (o.color[1] * jg).min(1.0), + (o.color[2] * jb).min(1.0), + ); + q.size = 0.26; + q.lifetime = duration; + q.has_physics = false; + q.free_move = true; + q.light = Light::FullBright; + q.behaviour = Behaviour::Trail { target }; + q + } }; if particle.set.is_some() { particle.sprite = self.first(ty); @@ -2146,6 +2185,19 @@ impl ParticleEngine { start[2] + p.velocity[2] * f64::from(pos), ]; } + Behaviour::Trail { target } => { + p.previous = p.position; + let age = p.age; + p.age += 1; + if age >= p.lifetime { + p.removed = true; + return; + } + let alpha = 1.0 / f64::from((p.lifetime - p.age).max(1)); + for i in 0..3 { + p.position[i] += (target[i] - p.position[i]) * alpha; + } + } Behaviour::HugeExplosion => { p.previous = p.position; let age = p.age; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 83e93e8e1..1b532c59b 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -400,6 +400,11 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b entries.push(("Page", Tag::Int(l.page))); } } + BlockEntity::CreakingHeart(h) => { + if let Some((_, uuid)) = h.creaking { + entries.push(("creaking", uuid_tag(uuid))); + } + } } Tag::compound(entries) } @@ -421,6 +426,13 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }), )); } + if id == "minecraft:creaking_heart" { + let heart = crate::containers::CreakingHeart { + creaking: uuid_from_tag(tag.get("creaking")).map(|uuid| (None, uuid)), + ..Default::default() + }; + return Some((pos, BlockEntity::CreakingHeart(Box::new(heart)))); + } if id == "minecraft:lectern" { let lectern = crate::containers::Lectern { book: tag.get("Book").and_then(item_from_nbt), @@ -474,7 +486,10 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers: }; } BlockEntity::Sign(sign) => sign.decode(tag), - BlockEntity::Jukebox(_) | BlockEntity::Beacon(_) | BlockEntity::Lectern(_) => {} + BlockEntity::Jukebox(_) + | BlockEntity::Beacon(_) + | BlockEntity::Lectern(_) + | BlockEntity::CreakingHeart(_) => {} } Some((pos, entity)) } @@ -2063,6 +2078,37 @@ mod tests { assert_eq!((r[1] >> 12) & 0xF, 4, "version 4"); } #[test] + fn creaking_heart_keeps_its_protector_uuid() { + use crate::containers::{BlockEntity, CreakingHeart}; + let heart = CreakingHeart { + creaking: Some((Some(7), [1, 2, 3, 4])), + ..Default::default() + }; + let tag = encode_block_entity( + (3, 70, -5), + &BlockEntity::CreakingHeart(Box::new(heart)), + "minecraft:creaking_heart", + ); + assert_eq!( + tag.get("creaking"), + Some(&Tag::IntArray(vec![1, 2, 3, 4])), + "vanilla stores the protector's UUID under `creaking`" + ); + let (pos, entity) = decode_block_entity(&tag).expect("heart decodes"); + assert_eq!(pos, (3, 70, -5)); + let BlockEntity::CreakingHeart(h) = entity else { + panic!("a creaking heart"); + }; + // The entity id is resolved again once the creaking is loaded. + assert_eq!(h.creaking, Some((None, [1, 2, 3, 4]))); + let lonely = encode_block_entity( + (0, 0, 0), + &BlockEntity::CreakingHeart(Box::default()), + "minecraft:creaking_heart", + ); + assert!(lonely.get("creaking").is_none()); + } + #[test] fn light_nibbles_use_vanilla_order() { let mut a = Box::new([0u8; 4096]); a[0] = 0xF3; // sky 15, block 3 at x=0 diff --git a/crates/horizon-world/src/level/creaking.rs b/crates/horizon-world/src/level/creaking.rs new file mode 100644 index 000000000..07633c978 --- /dev/null +++ b/crates/horizon-world/src/level/creaking.rs @@ -0,0 +1,83 @@ +//! The creaking heart block (`CreakingHeartBlock`): its state follows the +//! pale oak logs on both ends of its axis and the `creaking_active` +//! environment attribute. The block entity (protector, particles, resin) +//! lives with the entities in the client. +use super::{Behaviours, Dimension, LevelAccess, Sim, Ticks, update::rel}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, position::BlockPos}; + +/// `Direction.Axis.getDirections()`. +fn axis_directions(axis: &str) -> [Direction; 2] { + match axis { + "x" => [Direction::West, Direction::East], + "z" => [Direction::North, Direction::South], + _ => [Direction::Down, Direction::Up], + } +} + +impl Sim<'_, L> { + /// `EnvironmentAttributes.CREAKING_ACTIVE`: the overworld day timeline + /// turns it on from 12600 to 23400. + pub(crate) fn creaking_active(&self) -> bool { + self.level.dimension() == Dimension::Overworld + && (12600..23401).contains(&self.level.day_time().rem_euclid(24000)) + } + /// `CreakingHeartBlock.hasRequiredLogs`: pale oak logs along the axis. + pub(crate) fn heart_has_required_logs(&self, state: BlockStateId, pos: BlockPos) -> bool { + let b = self.b; + let axis = b.table.text(state, b.props.axis); + axis_directions(axis).into_iter().all(|d| { + let neighbour = self.state(rel(pos, d)); + b.in_set(neighbour, &b.tags.pale_oak_logs) + && b.table.text(neighbour, b.props.axis) == axis + }) + } + /// `CreakingHeartBlock.updateState`: an uprooted heart with its logs wakes + /// (at night) or goes dormant. + pub(crate) fn heart_update_state(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + let b = self.b; + let uprooted = b.table.text(state, b.props.creaking_heart_state) == "uprooted"; + if uprooted && self.heart_has_required_logs(state, pos) { + let next = if self.creaking_active() { + "awake" + } else { + "dormant" + }; + b.table.set_text(state, b.props.creaking_heart_state, next) + } else { + state + } + } + /// `CreakingHeartBlock.tick` (scheduled by `updateShape`). + pub(crate) fn heart_tick(&mut self, state: BlockStateId, pos: BlockPos) { + let next = self.heart_update_state(state, pos); + if next != state { + self.set_block_and_update(pos, next); + } + } + /// `CreakingHeartBlock.getStateForPlacement` after the axis is set. + pub(crate) fn heart_placement(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId { + self.heart_update_state(state, pos) + } +} + +impl Behaviours { + /// `EnvironmentAttributes.CREAKING_ACTIVE` at the level's time. + pub fn creaking_active( + &self, + level: &mut L, + ticks: &mut Ticks, + ) -> bool { + self.sim(level, ticks).creaking_active() + } + /// `CreakingHeartBlock.hasRequiredLogs`. + pub fn creaking_heart_has_logs( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + state: BlockStateId, + ) -> bool { + self.sim(level, ticks).heart_has_required_logs(state, pos) + } +} diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 73efe9158..e66b086e6 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -451,6 +451,7 @@ tags! { enables_bubble_column_push_up = "enables_bubble_column_push_up", enables_bubble_column_drag_down = "enables_bubble_column_drag_down", shulker_boxes = "shulker_boxes", + pale_oak_logs = "pale_oak_logs", convertible_to_mud = "convertible_to_mud", grows_crops = "grows_crops", candles = "candles", @@ -553,6 +554,7 @@ props! { honey_level = "honey_level", bloom = "bloom", natural = "natural", + creaking_heart_state = "creaking_heart_state", cracked = "cracked", has_book = "has_book", signal_fire = "signal_fire", diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 1a05bbb11..1a0cdaa20 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -102,6 +102,7 @@ pub mod ticks; mod bonemeal; mod buckets; +mod creaking; mod falling; mod feature_world; mod fluids; diff --git a/crates/horizon-world/src/level/place.rs b/crates/horizon-world/src/level/place.rs index 01e9527c2..401288c3e 100644 --- a/crates/horizon-world/src/level/place.rs +++ b/crates/horizon-world/src/level/place.rs @@ -786,7 +786,12 @@ impl Sim<'_, L> { ); Some(table.set_text(default, p.orientation, &orientation)) } - Class::CreakingHeart | Class::RotatedPillar | Class::InfestedRotatedPillar => { + Class::CreakingHeart => { + let state = + table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face))); + Some(self.heart_placement(state, ctx.pos)) + } + Class::RotatedPillar | Class::InfestedRotatedPillar => { Some(table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face)))) } Class::DecoratedPot => { diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 28c9ac73d..6e53a9fa3 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -43,6 +43,7 @@ pub(crate) struct TestLevel { air: BlockStateId, random: LegacyRandom, pub time: i64, + pub day_time: i64, pub events: Vec, pub block_light: HashMap, } @@ -53,6 +54,7 @@ impl TestLevel { air: b.air(), random: LegacyRandom::new(42), time: 0, + day_time: 0, events: Vec::new(), block_light: HashMap::new(), } @@ -74,6 +76,9 @@ impl LevelAccess for TestLevel { fn game_time(&self) -> i64 { self.time } + fn day_time(&self) -> i64 { + self.day_time + } fn block_light(&self, pos: BlockPos) -> i32 { self.block_light.get(&pos).copied().unwrap_or(0) } @@ -980,3 +985,48 @@ fn dispenser_buckets_pick_up_and_empty() { )); assert_eq!(w.name(at), "powder_snow[]"); } + +#[test] +fn creaking_heart_follows_its_logs_and_the_night() { + let mut w = world!(); + let heart_at = BlockPos::new(0, 10, 0); + let log = |w: &World, axis: &str| w.id("pale_oak_log", &[("axis", axis)]); + let heart = w.id( + "creaking_heart", + &[("axis", "y"), ("creaking_heart_state", "uprooted")], + ); + let (below, above) = (BlockPos::new(0, 9, 0), BlockPos::new(0, 11, 0)); + w.put(heart_at, heart); + w.put(below, log(&w, "y")); + // A log along another axis does not count. + w.put(above, log(&w, "x")); + assert!( + !w.b() + .creaking_heart_has_logs(&mut w.level, &mut w.ticks, heart_at, heart) + ); + // Day: a log update wakes the uprooted heart to dormant. + let up = log(&w, "y"); + w.set(above, up); + for _ in 0..3 { + w.tick(); + } + assert_eq!(w.prop(heart_at, "creaking_heart_state"), "dormant"); + // Night: the same trunk wakes a fresh heart up. + w.level.day_time = 14000; + w.put(heart_at, heart); + w.put(above, w.b().air()); + w.set(above, up); + for _ in 0..3 { + w.tick(); + } + assert_eq!(w.prop(heart_at, "creaking_heart_state"), "awake"); + // Placed without logs it stays uprooted. + w.put(above, w.b().air()); + w.put(heart_at, heart); + let air = w.b().air(); + w.set(above, air); + for _ in 0..3 { + w.tick(); + } + assert_eq!(w.prop(heart_at, "creaking_heart_state"), "uprooted"); +} diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 0723af984..e8eda53cf 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -146,6 +146,7 @@ impl Sim<'_, L> { } Class::Observer => self.observer_tick(pos, state), Class::Eyeblossom => self.eyeblossom_tick(state, pos, false), + Class::CreakingHeart => self.heart_tick(state, pos), Class::DriedGhast => self.dried_ghast_tick(state, pos), Class::RedstoneLamp => self.lamp_tick(pos, state), Class::RedstoneTorch => self.torch_tick(pos, state),